<?php
function get_all_internal_pages(){
	$all_pages = new WP_Query(array(
		'post_type' 		=> 'page',
		'posts_per_page' 	=> -1,
		'post_status' 		=> 'publish',
		'orderby' 			=> 'date',
		'order' 			=> 'DESC',
	)
);
	$data = $all_pages->posts;
	return $data;
}
function save_redirection($data){
	global $wpdb;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$wpdb->insert( $redirection_table,$data);
	$last_id = $wpdb->insert_id;
	$redirection_details=$wpdb->get_row("SELECT * FROM $redirection_table WHERE id=".$last_id);
	return $redirection_details;
}
function check_redirection($user_role){
	global $wpdb;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$redirection_details=$wpdb->get_row("SELECT * FROM $redirection_table WHERE user_role='".$user_role."'");
	return $redirection_details;
}
function redirection_details_by_id($id){
	global $wpdb;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$redirection_details=$wpdb->get_row("SELECT * FROM $redirection_table WHERE id=".$id);
	return $redirection_details;
}
function get_all_rules(){
	global $wpdb;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$redirection_details=$wpdb->get_results("SELECT * FROM $redirection_table");
	return $redirection_details;
}
function update_redirection($id,$data){
	global $wpdb;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$wpdb->update($redirection_table, $data,array('id'=>$id));
	$redirection_details=$wpdb->get_row("SELECT * FROM $redirection_table WHERE id=".$id);
	return $redirection_details;
}
function delete_redirection($id){
	global $wpdb;
	$delete_item=false;
	$redirection_table = $wpdb->prefix.'corsair_redirection';
	$delete=$wpdb->query("DELETE FROM $redirection_table WHERE id=".$id);
	if($delete){
		$delete_item=true;
	}
	return $delete_item;

}
function get_all_redirection_rules(){
	$html='';
	$all_redirecion_rule=get_all_rules();
	if(!empty($all_redirecion_rule)){
		foreach ($all_redirecion_rule as $key_rule => $value_rule) {
			if($value_rule->url_source=='internal'){
				$link=get_the_permalink($value_rule->redirection_url);
			}
			else{
				$link=$value_rule->redirection_url;
			}
			$status=($value_rule->status == 1) ? 'checked' : '';
			$status_value=($value_rule->status == 1) ? '2' : '1';
			$html.='<tr class="role-section">';
			$html.='<td>'.ucfirst($value_rule->user_role).'</td>';
			$html.='<td>'.ucfirst($value_rule->url_source).'</td>';
			$html.='<td>'.$link.'</td>';
			$html.='<td><label class="switch"><input onclick="change_status('.$value_rule->id.','.$status_value.')" type="checkbox" '.$status.'><span class="slider round"></span></label></td>';
			$html.='<td class="action"><span class="dashicons dashicons-edit-large" title="Update Redirection" onclick="update_redirecion('.$value_rule->id.')"></span> <span class="dashicons dashicons-trash" title="Delete Redirection" onclick="delete_redirecion('.$value_rule->id.')"></span></td>';
			$html.='</tr>';
		}
	}
	else{
		$html.='<tr class="role-section">';
		$html.='<td colspan="5">'.__("Nothing Found" , "corsair-login").'</td>';
		$html.='</tr>';
	}
	return $html;
}
function get_redirection_pages($url_source){
	$html='';
	$all_pages=get_all_internal_pages();
	if($url_source!='' && $url_source=='internal'){
		$html='<select name="redirection_link" class="redirection_link">';
		$html.='<option value="">'.__("Select Page" , "corsair-login").'</option>';
		foreach ($all_pages as $key_page => $value_page) {

			$html.='<option value="'.$value_page->ID.'">'.get_the_title($value_page->ID).'('.$value_page->post_name.')</option>';

		}
		$html.='</select>';
		$html.='<span class="redirection-link-error"></span>';
	}
	elseif($url_source!='' && $url_source=='external'){
		$html='<input type="text" name="redirection_link" class="redirection_link" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection-link-error"></span>';
	}
	else{
		$html='<input type="text" name="redirection_link" class="redirection_link" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection-link-error"></span>';
	}
	return $html;
}
function get_selected_page($page_id,$value=''){
	$selected='';
	if($page_id==$value){
		$selected='selected';
	}
	return $selected;
}
function get_selected_source($source,$value){
	$selected='';
	if($source==$value){
		$selected='selected';
	}
	return $selected;
}
function get_redirection_update_html($id){
	$html='';
	$all_pages=get_all_internal_pages();
	$redirection_details=redirection_details_by_id($id);
	$url_source=$redirection_details->url_source;
	$user_role=$redirection_details->user_role;
	$redirection_url=$redirection_details->redirection_url;
	if($url_source!='' && $url_source=='internal' && $user_role!=''){
		$html='<h3>'.__("Update Redirection" , "corsair-login").'</h3>';
		$html.='<div class="loading-image" id="lodingimages_popup_update">';
		$html.='<img src="'.PLUGIN_URL.'/image/loading.gif">';
		$html.='</div>';
		$html.='<div class="source_section">';
		$html.='<select name="redirection_source_update" class="redirection_source_update">';
		$html.='<option value="internal" '.get_selected_source($url_source,'internal').'>'.__("Internal" , "corsair-login").'</option>';
		$html.='<option value="external" '.get_selected_source($url_source,'external').'>'.__("External" , "corsair-login").'</option>';
		$html.='</select>';
		$html.='<span class="redirection_source_update-error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<div class="redirection_section">';
		$html.='<select name="redirection_link_update" class="redirection_link_update">';
		$html.='<option value="">'.__("Select Page" , "corsair-login").'</option>';
		foreach ($all_pages as $key_page => $value_page) {
			if($redirection_url==$value_page->ID){
				$selected='selected';
			}
			else{
				$selected='';
			}
			$html.='<option value="'.$value_page->ID.'" '.$selected.'>'.get_the_title($value_page->ID).'</option>';

		}
		$html.='</select>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<input type="hidden" name="user_role_redirect_update" id="user_role_redirect_update" value="'.$user_role.'">';
		$html.='<input type="hidden" name="redirection_id" id="redirection_id" value="'.$id.'">';
		$html.='<span class="redirection_update-error" style="disply:none;"></span>';
		$html.='<button type="button" class="button-primary btn-redirection-update">'.esc_attr('Update', 'corsair-login').'</button>';
	}
	elseif($url_source!='' && $url_source=='external' && $user_role!=''){
		$html='<h3>Update Redirection</h3>';
		$html.='<div class="loading-image" id="lodingimages_popup_update">';
		$html.='<img src="'.PLUGIN_URL.'/image/loading.gif">';
		$html.='</div>';
		$html.='<div class="source_section">';
		$html.='<select name="redirection_source_update" class="redirection_source_update">';
		$html.='<option value="internal" '.get_selected_source($url_source,'internal').'>'.__("Internal" , "corsair-login").'</option>';
		$html.='<option value="external" '.get_selected_source($url_source,'external').'>'.__("External" , "corsair-login").'</option>';
		$html.='</select>';
		$html.='<span class="redirection_source_update-error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<div class="redirection_section">';
		$html.='<input type="text" name="redirection_link_update" class="redirection_link_update" value="'.$redirection_url.'" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<input type="hidden" name="user_role_redirect_update" id="user_role_redirect_update" value="'.$user_role.'">';
		$html.='<input type="hidden" name="redirection_id" id="redirection_id" value="'.$id.'">';
		$html.='<span class="redirection_update-error" style="disply:none;"></span>';
		$html.='<button type="button" class="button-primary btn-redirection-update">'.esc_attr('Update', 'corsair-login').'</button>';
	}
	else{
		$html='<h3>Update Redirection</h3>';
		$html.='<div class="loading-image" id="lodingimages_popup_update">';
		$html.='<img src="'.PLUGIN_URL.'/image/loading.gif">';
		$html.='</div>';
		$html.='<div class="source_section">';
		$html.='<select name="redirection_source_update" class="redirection_source_update">';
		$html.='<option value="internal" '.get_selected_source($url_source,'internal').'>Internal</option>';
		$html.='<option value="external" '.get_selected_source($url_source,'external').'>External</option>';
		$html.='</select>';
		$html.='<span class="redirection_source_update-error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<div class="redirection_section">';
		$html.='<input type="text" name="redirection_link_update" class="redirection_link_update" value="'.$redirection_url.'" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
		$html.='</div>';
		$html.='<input type="hidden" name="user_role_redirect_update" id="user_role_redirect_update" value="'.$user_role.'">';
		$html.='<input type="hidden" name="redirection_id" id="redirection_id" value="'.$id.'">';
		$html.='<span class="redirection_update-error" style="disply:none;"></span>';

		$html.='<button type="button" class="button-primary btn-redirection-update">'.esc_attr('Update', 'corsair-login').'</button>';

	}
	return $html;
}
function link_html_by_source($url_source){
	$html='';
	$all_pages=get_all_internal_pages();
	if($url_source!='' && $url_source=='internal'){
		$html='<select name="redirection_link_update" class="redirection_link_update">';
		$html.='<option value="">'.__("Select Page" , "corsair-login").'</option>';
		foreach ($all_pages as $key_page => $value_page) {

			$html.='<option value="'.$value_page->ID.'">'.get_the_title($value_page->ID).'('.$value_page->post_name.')</option>';

		}
		$html.='</select>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
	}
	elseif($url_source!='' && $url_source=='external'){
		$html='<input type="text" name="redirection_link_update" class="redirection_link_update" value="'.$redirection_url.'" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
	}
	else{
		$html='<input type="text" name="redirection_link_update" class="redirection_link_update" value="'.$redirection_url.'" placeholder="'.__("Please enter external redirect url" , "corsair-login").'"/>';
		$html.='<span class="redirection_link_update_error" style="disply:none;"></span>';
	}
	return $html;
}
add_action( 'wp_ajax_nopriv_link_by_source', 'link_by_source' );
add_action( 'wp_ajax_link_by_source', 'link_by_source' );
function link_by_source(){
	$status=fasle;
	$html='';
	if(isset($_POST['action'])){
		$html=link_html_by_source($_POST['url_source']);
		$status=true;
	}
	$response = array('status' => $status, 'html' => $html);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_get_redirection_popup', 'get_redirection_popup' );
add_action( 'wp_ajax_get_redirection_popup', 'get_redirection_popup' );
function get_redirection_popup(){
	$status=fasle;
	$html='';
	if(isset($_POST['action'])){
		$html=get_redirection_pages($_POST['url_source']);
		$status=true;
	}
	$response = array('status' => $status, 'html' => $html);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_update_redirection_popup', 'update_redirection_popup' );
add_action( 'wp_ajax_update_redirection_popup', 'update_redirection_popup' );
function update_redirection_popup(){
	$status=fasle;
	$html='';
	if(isset($_POST['action'])){
		$html=get_redirection_update_html($_POST['id']);
		$status=true;
	}
	$response = array('status' => $status, 'html' => $html);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_add_redirection', 'add_redirection' );
add_action( 'wp_ajax_add_redirection', 'add_redirection' );
function add_redirection(){
	$status=fasle;
	$html='';
	$message='';
	if(isset($_POST['action'])){
		$data=array(
			'redirection_url'=>$_POST['link'],
			'url_source'=>$_POST['url_source'],
			'user_role'=>$_POST['user_role'],
			'status'=>1
		);

		$check_redirection=check_redirection($_POST['user_role']);
		if(!empty($check_redirection)){
			$status=false;
			$message='aleady_exist';
			$html.='<tr>';
			$html.='<th>'.__("User Role" , "corsair-login").'</th>';
			$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
			$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
			$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
			$html.='<th>'.__("Action" , "corsair-login").'</th>';
			$html.='</tr>';
			$html.=get_all_redirection_rules();
		}
		else{
			$save_data=save_redirection($data);
			if(!empty($save_data)){
				$status=true;
				$message='success';
				$html.='<tr>';
				$html.='<th>'.__("User Role" , "corsair-login").'</th>';
				$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
				$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
				$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
				$html.='<th>'.__("Action" , "corsair-login").'</th>';
				$html.='</tr>';
				$html.=get_all_redirection_rules();
			}
			else{
				$status=false;
				$message='error';
				$html.='<tr>';
				$html.='<th>'.__("User Role" , "corsair-login").'</th>';
				$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
				$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
				$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
				$html.='<th>'.__("Action" , "corsair-login").'</th>';
				$html.='</tr>';
				$html.=get_all_redirection_rules();
			}
		}
	}
	$response = array('status' => $status, 'html' => $html,'message' => $message);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_uppdate_redirection_rules', 'uppdate_redirection_rules' );
add_action( 'wp_ajax_uppdate_redirection_rules', 'uppdate_redirection_rules' );
function uppdate_redirection_rules(){
	$status=fasle;
	$html='';
	$message='';
	if(isset($_POST['action'])){
		$id=$_POST['id'];
		$data=array(
			'redirection_url'=>$_POST['link'],
			'url_source'=>$_POST['url_source'],
		);

		$update_redirection=update_redirection($id,$data);
		if(!empty($update_redirection)){
			$status=true;
			$message='success';
			$html.='<tr>';
			$html.='<th>'.__("User Role" , "corsair-login").'</th>';
			$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
			$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
			$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
			$html.='<th>'.__("Action" , "corsair-login").'</th>';
			$html.='</tr>';
			$html.=get_all_redirection_rules();
		}

		else{
			$status=false;
			$message='error';
			$html.='<tr>';
			$html.='<th>'.__("User Role" , "corsair-login").'</th>';
			$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
			$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
			$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
			$html.='<th>'.__("Action" , "corsair-login").'</th>';
			$html.='</tr>';
			$html.=get_all_redirection_rules();
		}

	}
	$response = array('status' => $status, 'html' => $html,'message' => $message);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_delete_redirection_rule', 'delete_redirection_rule' );
add_action( 'wp_ajax_delete_redirection_rule', 'delete_redirection_rule' );
function delete_redirection_rule(){
	$status=false;
	$html='';
	$message='';
	if(isset($_POST['action'])){
		$id=$_POST['id'];
		$delete_redirection=delete_redirection($id);

		$status=true;
		$message='success';
		$html.='<tr>';
		$html.='<th>'.__("User Role" , "corsair-login").'</th>';
		$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
		$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
		$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
		$html.='<th>'.__("Action" , "corsair-login").'</th>';
		$html.='</tr>';
		$html.=get_all_redirection_rules();
	}
	$response = array('status' => $status, 'html' => $html,'message' => $message);
	wp_send_json($response);
	exit;
}
add_action( 'wp_ajax_nopriv_update_status_redirection', 'update_status_redirection' );
add_action( 'wp_ajax_update_status_redirection', 'update_status_redirection' );
function update_status_redirection(){
	$status=false;
	$html='';
	$message='';
	if(isset($_POST['action'])){
		$id=$_POST['id'];
		$data=array(
			'status'=>$_POST['status']
		);

		$update_redirection=update_redirection($id,$data);
		if(!empty($update_redirection)){
			$status=true;
			$message='success';
			$html.='<tr>';
			$html.='<th>'.__("User Role" , "corsair-login").'</th>';
			$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
			$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
			$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
			$html.='<th>'.__("Action" , "corsair-login").'</th>';
			$html.='</tr>';
			$html.=get_all_redirection_rules();
		}

		else{
			$status=false;
			$message='error';
			$html.='<tr>';
			$html.='<th>'.__("User Role" , "corsair-login").'</th>';
			$html.='<th>'.__("URL Source" , "corsair-login").'</th>';
			$html.='<th>'.__("Redirection Link" , "corsair-login").'</th>';
			$html.='<th>Status<span class="tooltip"><span class="tooltiptext">'.__("Drag to change status, Redirection will not work utill it is inactive" , "corsair-login").'</span></span></th>';
			$html.='<th>'.__("Action" , "corsair-login").'</th>';
			$html.='</tr>';
			$html.=get_all_redirection_rules();
		}

	}
	$response = array('status' => $status, 'html' => $html,'message' => $message);
	wp_send_json($response);
	exit;
}
/**
 * ajax login script 28-03-2023
 */
function corsairlogin_client_ip(){
	global $corsairlogin_client_ip;
	if (!is_null($corsairlogin_client_ip)) {
		// We've already discovered the browser's IP address.
	} elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
		$corsairlogin_client_ip = filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP);
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		$corsairlogin_client_ip = filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP);
	} else {
		$corsairlogin_client_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
	}
	return $corsairlogin_client_ip;
}

// Login Security MFP
// To get distance of user current location and database locatioin
function getUserDistance($dbLat, $dbLon, $currentLat, $currentLon) {
    // Earth's radius in kilometers
    $earthRadius = 6371;

    // Convert degrees to radians
    $dbLat = deg2rad($dbLat);
    $dbLon = deg2rad($dbLon);
    $currentLat = deg2rad($currentLat);
    $currentLon = deg2rad($currentLon);

    // Calculate the differences
    $deltaLat = $currentLat - $dbLat;
    $deltaLon = $currentLon - $dbLon;

    // Apply Haversine formula
    $a = sin($deltaLat / 2) * sin($deltaLat / 2) +
         cos($dbLat) * cos($currentLat) *
         sin($deltaLon / 2) * sin($deltaLon / 2);

    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    // Calculate the distance
    $distance = $earthRadius * $c;
    return $distance;
}
//Get user geo location
function getUserGeolocation(){
	$ipAddress = $_SERVER['REMOTE_ADDR'];
	//Get aprox geolocation
	// $api_url_geolocation = "http://ip-api.com/json/{$ipAddress}";

	$api_key = get_option('vpn_api_key');
	// Fetch VPN and TOR detection data
	$geolocationResponse = wp_remote_get("https://vpnapi.io/api/{$ipAddress}?key={$api_key}");
	$response_code = wp_remote_retrieve_response_code($geolocationResponse);
	$geolocationData = json_decode(wp_remote_retrieve_body($geolocationResponse), true);


	// $geolocationResponse = file_get_contents($api_url_geolocation);
	// $geolocationData = json_decode($geolocationResponse, true);

	// if ($geolocationData['status'] === 'success') {
	if ($response_code != 429 && !is_wp_error($geolocationResponse) && !empty($geolocationData)) {
		$geolocation = [
			'country' => $geolocationData['location']['country'],
			'region' => $geolocationData['location']['region'],
			'city' => $geolocationData['location']['city'],
			'latitude' => $geolocationData['location']['latitude'],
			'longitude' => $geolocationData['location']['longitude']
		];
	}

	$log_details = 'Geo Location Main Call = ' . json_encode( $geolocation );
	create_corsairlogin_logs_entry(0,'GeoLocationMainCall','','user',$log_details,true);

	return $geolocation;
	//Get aprox geolocation END
}
//get user browser data
function getUserBrowser() {
	// Define a list of popular browsers
	$browserList = [
        'Brave' => 'Brave',
        'Tor Browser' => 'TorBrowser',
        'Edge' => 'Edg',
        'Opera' => 'OPR',
        'Vivaldi' => 'Vivaldi',
        'Yandex Browser' => 'YaBrowser',
        'UC Browser' => 'UCBrowser',
        'Samsung Internet' => 'SamsungBrowser',
        'QQ Browser' => 'QQBrowser',
        'Baidu Browser' => 'Baiduspider',
        'Maxthon' => 'Maxthon',
        'Puffin' => 'Puffin',
        'Sogou Browser' => 'MetaSr',
        '360 Browser' => '360SE',
        'Internet Explorer' => 'MSIE',
        'Internet Explorer 11' => 'Trident',
        'Chrome' => 'Chrome',
        'Firefox' => 'Firefox',
        'Safari' => 'Safari',
    ];
	$browserName = 'Unknown';
	$browserVersion = 'Unknown';
	// Get the user agent string
	$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';

	foreach ($browserList as $name => $pattern) {
		if (preg_match("/($pattern)/i", $userAgent, $matches)) {
			$browserName = $name;

			// Get the version number
			preg_match('/' . $matches[1] . '[\/\s](\d+(\.\d+)?)/', $userAgent, $versionMatch);
			$browserVersion = $versionMatch[1] ?? 'Unknown';
			break;
		}
	}
	return [
		'name' => $browserName,
		'version' => $browserVersion
	];
}
// Login Security MFP END

add_action('wp_ajax_nopriv_corsair_user_login', 'corsair_login_try_to_login_action');
function corsair_login_try_to_login_action(){
	if (empty($client_ip_address = corsairlogin_client_ip())) {
		die();
	}
	global $wpdb;
	$tableKyc = $wpdb->prefix.'kyc_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$client_key = 'login_attempt_' . $client_ip_address;
	$clientResendKey = 'resend_attempt_' . $client_ip_address;
	$status_code = 200;
	$response = array(
		'isLoggedIn' => false,
		'isResetRequested' => false,
		'pwdin' => false,
		'isOtpSend' => false,
		'isincorrectup' => false,
		'errorMessage' => '',
		'infoMessage' => '',
	);
	$routine_maintenance = get_option('cip_routine_maintenance_mode'); //live
	$site_maintenance = get_option('cip_site_maintenance_mode'); //whole
	if( $routine_maintenance == 1 || $site_maintenance == 1){
		if( !empty( $_POST['user_email'] )){
			$user = get_user_by( 'email', $_POST['user_email'] );
			$allowed_roles = array('supportmanager', 'supportagent');
			if( !array_intersect($allowed_roles, $user->roles ) ) {
				$response['errorMessage'] = "Site in maintenance, you cannot log in at this time. Please try again later.";
				wp_send_json(
					$response,
					$status_code
				);
				die();
			}
		}
	}


	if( wp_verify_nonce( $_POST['micro_nonce'],'corsair_login_request' ) ){
		if( !empty( $_POST['user_email'] ) && ( !isset( $_POST['user_password'] ) || empty( $_POST['user_password'] ) ) ){ // check email for reset or enter password

			$user_email = $_POST['user_email'];
			$getTokenHolderData = $wpdb->get_row("SELECT `email`,`username`,`first_name`,`last_name` FROM $tableTokenHolder WHERE 1 AND `email`='". $user_email ."' AND `email` <> '' AND `email` IS NOT NULL ORDER BY `id` DESC LIMIT 1");

			if ((get_transient($client_key) !== false)) {
				$response['errorMessage'] = 'Slow down a bit';
			} elseif (empty($user_email = $_POST['user_email'])) {
				$response['errorMessage'] = 'No user email';
			} elseif( !filter_var($user_email, FILTER_VALIDATE_EMAIL) ){
				$response['errorMessage'] = 'Invalid email';
			} elseif( email_exists( $user_email ) ){
				$user = get_user_by( 'email', $user_email );

				$activation_status = 1;
				if ( metadata_exists( 'user', $user->ID, 'csrmember_activation_status' ) ) {
					$activation_status = get_user_meta( $user->ID, 'csrmember_activation_status', true );
				}
				if( $activation_status != 1 ){

					$user_activation_key =  md5( uniqidReal() );
					// $encryptUsername = base64_encode( $user_id . md5('CiP@EmailVerification@PiC'));
					update_user_meta($user->ID, 'csrmember_activation_key', $user_activation_key);
					update_user_meta($user->ID, 'csrmember_activation_status', 0);

					$encryptedEmail = encrypt($user_email, $user_activation_key . "CIP2023CIP");

					$codeString = array('name'=>$encryptedEmail, 'activation_key'=>$user_activation_key);

					$unique_url = add_query_arg(
						array( 'verification_action' => base64_encode( serialize($codeString) )),
						get_permalink( get_page_by_path('content/operations/email-verification') )
					);

					$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
					$siteUrl = get_bloginfo('url');
					$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
					add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
					add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s',CIP_TXTDOMAIN), get_option('blogname') ); } );
					add_filter('wp_mail_content_type', function(){ return "text/html"; } );

					$subject = sprintf(__("Welcome to %s - Verify Your Email Address", CIP_TXTDOMAIN), $blogname);

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

					$unique_url_txt = disable_email_link( $unique_url );

					$message = sprintf( __('<br><p>Dear Supporter,</p> <p>Welcome to CSRnow , and thank you for registering!</p><p>Before you dive into the world of CSR and Plastic Neutrality with us, there\'s just one last step to activate your account. Please verify your email address by clicking the link below:</p> <p><a href="%s" target="_blank" REPLACE_STYLE>Verify Your Email Address</a></p><br>If the button above does not work, paste this link into your web browser:<br>%s<p>If you did not initiate this request, please ignore this email or contact us if you have concerns about unauthorized activity.</p><p>Regards,<br/>The CSRnow Team</p><p><i>Please do not reply to this email as it is sent from an unmonitored address.</i></p>', CIP_TXTDOMAIN), esc_url($unique_url), $unique_url_txt );
					$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 © CSRnow.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: Google Sans, 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( $user_email, $subject, $htmlContent );
					if( $sent_mail ){
						$response['errorMessage'] = __('You have not verified your email address. Please verify your email address. We have resent a verification email to your email address', 'corsair-login');

						//cip_logs
						$logs = sprintf( __('Email verification email resent at login of %s at %s', 'corsair-login'), $user_email, date_i18n('d/m/Y H:i A') );
						create_corsairlogin_logs_entry( $user->ID, 'login', '','member', $logs, true  );

					}else{
						$response['errorMessage'] = __('You have not verified your email address. Please verify your email address. We have already sent a verification email to your address', 'corsair-login');
					}
					wp_send_json(
						$response,
						$status_code
					);
					exit;
				}

				$isSupportManagerAgent = false;
				if( $user instanceof WP_User ) {
					$user_id = $user->ID;
					if( in_array( 'supportmanager', $user->roles ) || in_array( 'supportagent', $user->roles ) ){
						$isSupportManagerAgent = true;
					}
				}
				if( $isSupportManagerAgent === true ){
					$isLoginEnable = 1; //by pass manager / agent
				}else{
					$isLoginEnable = get_user_meta( $user_id, 'csrnow_login_enable', true );
				}
				if( $isLoginEnable != 1 ){
					$response['errorMessage'] = __('Your account has been temporarily suspended.<br/>Please contact support.', 'corsair-login');
				}else{
					$response['pwdin'] = true;
				}
				// $response['errorMessage'] = __('Enter password','corsair-login');
			}else if( $getTokenHolderData ){	//check in token holder data
				if( !empty( $getTokenHolderData->email ) && !empty( $getTokenHolderData->username ) ){
					$user_email = $getTokenHolderData->email;
					$username = $getTokenHolderData->username;
					$user_password = wp_generate_password( 12, false );
					$user = wp_create_user( $username, $user_password, $user_email );
					if( !is_wp_error($user) ){
						$user = get_user_by( 'email', $user_email );
						if( $user instanceof WP_User ) {
							$user->add_role( 'member' );
							$user->remove_role( 'subscriber' );
							$user_id = $user->ID;
							$user_info = get_userdata($user_id);

							update_user_meta( $user_id, 'csrnow_login_enable', 1 );

							$unique = get_password_reset_key( $user_info );
							$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');

							$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
							$siteUrl = get_bloginfo('url');
							$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
							add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
							add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
							add_filter('wp_mail_content_type', function(){ return "text/html"; } );

							$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

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

							$unique_url_txt = disable_email_link( $unique_url );

							$message = sprintf(__('<br><p>This is an e-mail from %s.</p> <p>You are receiving this email because we received a password reset request for your account.</p><br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );
							$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 © CSRnow.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: Google Sans, 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( $user_email, $subject, $htmlContent );

							if ( !$sent_mail ){
								$response['errorMessage'] = __('There was a problem sending you email. Please try again or contact an admin.', 'corsair-login');
							}else{
								$response['errorMessage'] = sprintf( __('To increase account security, you are required to set a password on %s.<br/><br/>We have sent you link to set the password.', 'corsair-login'), $siteUrlName );
								$response['isResetRequested'] = true;
								update_user_meta( $user_id, 'cssetautologin', 1 );

								//cip_logs
								$logs = sprintf( __('User registered & password reset link sent of %s at %s (tokenholder)', 'corsair-login'), $user_email, date_i18n('d/m/Y H:i A') );
								create_corsairlogin_logs_entry( $user->ID, 'login', '','member', $logs, true  );
							}

						}else{
							$response['errorMessage'] = __('Something went wrong. Please try again.');
						}
					}else{
						$response['errorMessage'] = $user->get_error_message();
					}
				}else{
					$response['errorMessage'] = 'Email address or username not found.<br/>Use your Amplivo email to register.';
				}
			} else {
				$foundUser = corsair_get_users_from_sourceapi_data( $user_email );

				if( $foundUser['result'] ){
					$user_password = wp_generate_password( 12, false );
					$user = wp_create_user( $foundUser['Username'], $user_password, $user_email );
					if( !is_wp_error($user) ){
						$user = get_user_by( 'email', $user_email );
						if( $user instanceof WP_User ) {
							$user->add_role( 'member' );
							$user->remove_role( 'subscriber' );
							$user_id = $user->ID;
							$user_info = get_userdata($user_id);

							update_user_meta( $user_id, 'csrnow_login_enable', 1 );
							update_user_meta( $user_id, 'first_name', trim( $foundUser['first_name'] ) );
                            update_user_meta( $user_id, 'last_name', trim( $foundUser['last_name'] ) );

							$unique = get_password_reset_key( $user_info );
							$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');

							$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
							$siteUrl = get_bloginfo('url');
							$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
							add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
							add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
							add_filter('wp_mail_content_type', function(){ return "text/html"; } );

							$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

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

							$unique_url_txt = disable_email_link( $unique_url );

							$message = sprintf(__('<br><p>This is an e-mail from %s.</p> <p>You are receiving this email because we received a password reset request for your account.</p><br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );
							$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 © CSRnow.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: Google Sans, 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( $user_email, $subject, $htmlContent );

							if ( !$sent_mail ){
								$response['errorMessage'] = __('There was a problem sending you email. Please try again or contact an admin.', 'corsair-login');
							}else{
								$response['errorMessage'] = sprintf( __('To increase account security, you are required to set a password on %s.<br/><br/>We have sent you link to set the password.', 'corsair-login'), $siteUrlName );
								$response['isResetRequested'] = true;
								update_user_meta( $user_id, 'cssetautologin', 1 );

								//cip_logs
								$logs = sprintf( __('User registered & password reset link sent of %s at %s (amplivo)', 'corsair-login'), $user_email, date_i18n('d/m/Y H:i A') );
								create_corsairlogin_logs_entry( $user->ID, 'login', '','member', $logs, true  );
							}

						}else{
							$response['errorMessage'] = __('Something went wrong. Please try again.');
						}
					}else{
						$response['errorMessage'] = $user->get_error_message();
					}

				}else{
					$response['errorMessage'] = 'Email address not found.<br/>Use your Amplivo email to register.';
				}


			}
		}else{ //regular login script
			if ((get_transient($client_key) !== false)) {
				$response['errorMessage'] = 'Slow down a bit';
			} elseif (empty($user_email = $_POST['user_email'])) {
				$response['errorMessage'] = 'No user email';
			} elseif (empty($user_password = $_POST['user_password'])) {
				$response['errorMessage'] = 'No password';
			} elseif( !filter_var($user_email, FILTER_VALIDATE_EMAIL) ){
				$response['errorMessage'] = 'Invalid email';
			} elseif (!is_a($user = wp_authenticate($user_email, $user_password), 'WP_User')) {
				$response['errorMessage'] = 'Invalid email or password';
				$response['isincorrectup'] = true;
			}else {

				$user = wp_authenticate($user_email, $user_password);
				if( !is_wp_error($user) ){
					$user_id = $user->ID;

					// Login Security MFP

					//check if user is using VPN or TOR
					$ip = $_SERVER['REMOTE_ADDR'];
					$table_user_login_info = $wpdb->prefix . 'user_login_info';
					$ip_exists = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_user_login_info WHERE ip = %s", $ip));

					if (!$ip_exists) {
						// Check if the IP is localhost (to avoid blocking admin and local testing)
						if ($ip === '127.0.0.1' || $ip === '::1') {
							return; // Skip localhost
						}
						$api_key = get_option('vpn_api_key');
						//get the settings
						$check_vpn = get_option('vpn_switch_toggle', false);
						$check_proxy = get_option('proxy_switch_toggle', false);
						$check_tor = get_option('tron_switch_toggle', false);

						// Fetch VPN and TOR detection data
						$response = wp_remote_get("https://vpnapi.io/api/{$ip}?key={$api_key}");
						$response_code = wp_remote_retrieve_response_code($response);
						$data = json_decode(wp_remote_retrieve_body($response), true);

						$log_details = $_POST['user_email'] .' VPN API called.';
						create_corsairlogin_logs_entry($user->ID,'VPN API call','','user',$log_details,true);

						// If the API request limit is reached or any other error occurs
						if ($response_code === 429 || is_wp_error($response) || empty($data)) {
							create_corsairlogin_logs_entry(
								$user_id,
								'VPN api limit',
								'',
								'user',
								'VPN API request limit reached',
								true
							);
						}

						// Check if the API response detects a VPN or TOR
						$violation = false;
						$error_message = 'Access denied: ';
						if ($response_code != 429) {
							$violations = [];
							if ($check_vpn && isset($data['security']['vpn']) && $data['security']['vpn'] === true) {
								$violations[] = 'VPNs';
							}

							if ($check_proxy && isset($data['security']['proxy']) && $data['security']['proxy'] === true) {
								$violations[] = 'Proxies';
							}

							if ($check_tor && isset($data['security']['tor']) && $data['security']['tor'] === true) {
								$violations[] = 'TOR';
							}
						}

						if (!empty($violations)) {
							$formatted_violations = implode(' and ', array_filter([implode(', ', array_slice($violations, 0, -1)), end($violations)]));

							$response['errorMessage'] = "Access denied: " . $formatted_violations . " connections are not allowed on this site.";

							wp_send_json($response, $status_code);
							die();
						}
					}
					//check if user is using VPN or TOR ENDDD

					if (isset($_POST['user_info'])) {
						$deviceInfo = json_decode(stripslashes($_POST['user_info']));
					}

					$userDevice = $deviceInfo->device_type.' ('.$deviceInfo->os.')';

					if(in_array( 'administrator', $check_user->roles, true ) || in_array( 'supportmanager', $check_user->roles, true )){
						//if admin
						if (filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
							// Input is email
							$user = get_user_by('email', $_POST['user_email']);
						} else {
							// Input is a username
							$user = get_user_by('login', $_POST['user_email']);
						}
						$userId = $user->ID;
					}else{
						//user
						$userId = $user_id ;
					}

					$table_user_login_info = $wpdb->prefix . 'user_login_info';

					//deleting record of user older than 14 days
					$wpdb->query(
						$wpdb->prepare(
							"DELETE FROM $table_user_login_info
							WHERE `user_id` = %d
							AND `date` < DATE_SUB(CURDATE(), INTERVAL 14 DAY)",
							$userId
						)
					);
					$send_mfp_otp_email = 'no';
					$update_userInfo = "no";
					//if "" then not active
					$google_auth_key = get_user_meta( $userId, 'google_auth_key', true );
					$google_auth_key_login = get_user_meta( $userId, 'google_auth_key_login', true );
					$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_login == 1 ) ? 1 : 0;

					//if 1 acitve
					$user_email_otp_code = get_user_meta( $userId, 'otp_auth_key', true );

					if( $ga2fa_login_enabled != 1 && $user_email_otp_code != 1 ){

						if (isset($_POST['user_info'])) {
							$user_info = json_decode(stripslashes($_POST['user_info']));
						}

						// Collect HTTP headers
						$userAgent = $_SERVER['HTTP_USER_AGENT'];
						$ipAddress = $_SERVER['REMOTE_ADDR'];
						$user_info->user_agent = $userAgent;
						$user_info->ip = $ipAddress;

						$browser= getUserBrowser();
						$user_info->browser_name = $browser['name'];
						$user_info->browser_version = $browser['version'];

						$vpnapi_geolocation = $_SESSION['vpnapi_geolocation'];
						if( isset( $_POST['user_mfp_otp'] ) && !empty( $vpnapi_geolocation ) ){
							$geolocation= $vpnapi_geolocation;
						}else{
							$geolocation= getUserGeolocation();
							$_SESSION['vpnapi_geolocation'] = $geolocation;
						}

						$geolocationDataJson = wp_json_encode($geolocation);
						$user_info->geo_location = $geolocationDataJson;
						$currentLat = $geolocation['latitude'] ;
						$currentLon = $geolocation['longitude'];

						$device_id = $_COOKIE['device_id'];


						if($device_id !=""){
							$results = $wpdb->get_results(
								$wpdb->prepare(
									"SELECT * FROM $table_user_login_info
									WHERE user_id = %d
										AND device_id = %s
										AND os = %s
										AND os_version = %s
										AND device_type = %s
										AND language = %s
										AND browser_name = %s
										AND browser_version = %s
										AND user_agent = %s
										AND local_timezone = %s
										AND cookies_enabled = %d
										AND javascript_enabled = %d
										AND do_not_track_setting = %d",
									$userId,
									$device_id,
									$user_info->os,
									$user_info->os_version,
									$user_info->device_type,
									$user_info->language,
									$user_info->browser_name,
									$user_info->browser_version,
									$user_info->user_agent,
									$user_info->local_timezone,
									(int) $user_info->cookies_enabled,
									(int) $user_info->javascript_enabled,
									(int) $user_info->do_not_track_setting
								)
							);
						}else{

							$results = $wpdb->get_results(
								$wpdb->prepare(
									"SELECT * FROM $table_user_login_info
									WHERE user_id = %d
										AND ip = %s
										AND os = %s
										AND os_version = %s
										AND device_type = %s
										AND language = %s
										AND browser_name = %s
										AND browser_version = %s
										AND user_agent = %s
										AND local_timezone = %s
										AND cookies_enabled = %d
										AND javascript_enabled = %d
										AND do_not_track_setting = %d",
									$userId,
									$user_info->ip,
									$user_info->os,
									$user_info->os_version,
									$user_info->device_type,
									$user_info->language,
									$user_info->browser_name,
									$user_info->browser_version,
									$user_info->user_agent,
									$user_info->local_timezone,
									(int) $user_info->cookies_enabled,
									(int) $user_info->javascript_enabled,
									(int) $user_info->do_not_track_setting
								)
							);
						}


						if(!empty( $results )){
							$dbLat = json_decode($results[0]->geo_location)->latitude;
							$dbLon = json_decode($results[0]->geo_location)->longitude;

							$latitude_comparison = (floatval($currentLat) === floatval($dbLat)) ? true : false;
							$longitude_comparison = (floatval($currentLon) === floatval($dbLon)) ? true : false;

							//update MFP record if current lat long is diffrent then database
							if($latitude_comparison != true || $longitude_comparison != true || !empty($results) ){
								//lat or long has difference update MFP record
								$update_userInfo = "yes";
							}

							//get user distance from db and current location
							$distance = getUserDistance($dbLat, $dbLon, $currentLat, $currentLon);

							if($distance > 400 && !isset($_POST['user_mfp_otp'])){
								//if this variable is yes will send MFP otp email
								$send_mfp_otp_email = 'yes';
							}

						}else if(!isset($_POST['user_mfp_otp'])){
							//if this variable is yes will send MFP otp email
							$send_mfp_otp_email = 'yes';
						}

						$local_timezone = $user_info->local_timezone;
						$os = $user_info->os;
						$os_version = $user_info->os_version;
						$device_type = $user_info->device_type;
						$language = $user_info->language;
						$cookies_enabled = $user_info->cookies_enabled;
						$javascript_enabled = $user_info->javascript_enabled;
						$do_not_track_setting = $user_info->do_not_track_setting;
						$user_agent = $user_info->user_agent;
						$ip = $user_info->ip;
						$browser_name = $user_info->browser_name;
						$browser_version = $user_info->browser_version;
						$geo_location = $user_info->geo_location;

					}
					// Login Security MFP END

					$isSupportManagerAgent = false;
					if( in_array( 'supportmanager', $user->roles ) || in_array( 'supportagent', $user->roles ) ){
						$isSupportManagerAgent = true;
					}
					if( $isSupportManagerAgent === true ){
						$isLoginEnable = 1; //by pass manager / agent
					}else{
						$isLoginEnable = get_user_meta( $user_id, 'csrnow_login_enable', true );
					}

					if( $isLoginEnable != 1 ){
						$response['errorMessage'] = __('Your account has been temporarily suspended.<br/>Please contact support.', 'corsair-login');
						wp_send_json(
							$response,
							$status_code
						);
						exit;
					}

					$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
					$siteUrl = get_bloginfo('url');
					$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
					add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
					add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
					add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );
					if($user){
						$remember = ( isset( $_POST['remember'] ) && $_POST['remember'] == 1 ) ? true : false;
						$user_id = $user->ID;
						$isLoginType = get_login_auth_type( $user_id );

						if( $isLoginType['status'] == true && $isLoginType['type'] == 'both' ){

							if( isset( $_POST['switch_method'] ) && !empty( $_POST['switch_method'] ) ){
								$decryptedSwitchRaw = base64_decode( $_POST['switch_method'] );
								if( $decryptedSwitchRaw == md5( 'Email_OTP_Switch' ) ){ //switch to email
									$isLoginType['type'] = 'otp';
								}else if( $decryptedSwitchRaw == md5( 'Google_2FA_Switch' ) ){ //switch to google 2fa
									$isLoginType['type'] = '2fa';
								}else{
									$response['errorMessage'] = __('User authentication failed. Please try again or contact an admin', 'corsair-login');
								}
							}else{
								if( isset( $_POST['activetype'] ) && !empty( $_POST['activetype'] ) ){
									$decryptedActiveType = base64_decode( $_POST['activetype'] );
									if( $decryptedActiveType == md5( 'EmailOtp' ) ){ //continue to email otp
										$isLoginType['type'] = 'otp';
									}else if( $decryptedActiveType == md5( 'GoogleAuth2FA' ) ){ //continue to google 2FA
										$isLoginType['type'] = '2fa';
									}else{
										$response['errorMessage'] = __('User authentication failed. Please try again or contact an admin', 'corsair-login');
									}
								}else{
									$isLoginType['type'] = '2fa';
								}
							}

						}

						if( $isLoginType['status'] == true && $isLoginType['type'] == 'otp' ){
							if( isset( $_POST['resendOtpAct'] ) && $_POST['resendOtpAct'] == 1 ){ //resend OTP

								if ((get_transient($clientResendKey) !== false)) {
									$response['errorMessage'] = __('You can resend OTP after timer reset', 'corsair-login');
								}else{
									$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
									$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
									if( $decryptedUserId == $user_id ){
										$user_otp = sprintf("%'.06d",mt_rand(0,999999));
										$user_otp_expiration = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +30 mins"));
										$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
										update_user_meta( $user_id, 'user_otp', $user_otp );
										update_user_meta( $user_id, 'user_otp_expiration', $user_otp_expiration );

										$siteUrl = get_bloginfo('url');
										$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

										add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
										add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
										add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

										$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
										$message = sprintf(__('<h2>You are Attempting to Login in %s</h2><p>Here is your OTP (One-Time-Passcode) to login.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
										$htmlContent = mailTemplateHtmlRender( $message );
										$sent_mail = wp_mail( $user->user_email, $subject, $htmlContent );
										if( $sent_mail ){
											$response['isOtpSend'] = true;
											$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));

											$encryptSwitchType = base64_encode( md5('Google_2FA_Switch') );
											$activeType = base64_encode( md5('EmailOtp') );

											set_transient($clientResendKey, '1', 60);
											ob_start();
											?>
											<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
											<input type="hidden" name="activetype" value="<?php echo $activeType; ?>"  />
											<div class="otp_section pb-3">
												<label for="user_email"><?php echo __('Please enter the OTP', 'corsair-login'); ?></label>
												<input type="text" name="user_otp" id="user_otp" class="input" maxlength="6" pattern="{0-9}+" />
												<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
											</div>
											<input type="submit" name="wpa-submit-verify" id="wpa-submit-verify" class="btn btn-primary" value="<?php echo __('Verify OTP', 'corsair-login'); ?>" />
											<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).' s' : 'Resend OTP' ?></a>
											<script>
												jQuery(document).ready(function($){
													var is_countdown_resend = $('body').find('#resend').attr('data-stat') == 'countdown';
													if(is_countdown_resend){
														var sec = parseInt('<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>');
														var countdown = setInterval(() => {
															if(sec > 0){
																sec--;
																$('#resend').text("Resend in "+(sec)+' s')
															}else{
																$('#resend').attr('data-stat','').removeClass('disabled').text('Resend OTP')
																clearInterval(countdown)
															}
														}, 1000);
													}
												});
											</script>
											<?php
											if( $isLoginType['switch'] === true ){
												?><div class="switch-section"><a href="javascript:void(0);" class="switch-method" data-type="<?php echo $encryptSwitchType; ?>"><?php echo __('Switch to another verification method', 'corsair-login'); ?></a></div><?php
											}
											$otpContent = ob_get_clean();
											$response['otpContent'] = $otpContent;
										}else{
											$response['errorMessage'] = __('There was a problem sending OTP to your email. Please try again or contact an admin.', 'corsair-login');
										}
									}else{
										$response['errorMessage'] = __('User authentication failed. Please try again or contact an admin', 'corsair-login');
									}
								}

							}else if( !isset( $_POST['user_otp'] ) ){ //send OTP to user email
								$user_otp = sprintf("%'.06d",mt_rand(0,999999));
                				$user_otp_expiration = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +30 mins"));
                				$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
								update_user_meta( $user_id, 'user_otp', $user_otp );

								$siteUrl = get_bloginfo('url');
								$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

								add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
								add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
								add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

								update_user_meta( $user_id, 'user_otp_expiration', $user_otp_expiration );
								$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
								$message = sprintf(__('<h2>You are Attempting to Login in %s</h2><p>Here is your OTP (One-Time-Passcode) to login.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
								$htmlContent = mailTemplateHtmlRender( $message );
								$sent_mail = wp_mail( $user->user_email, $subject, $htmlContent );
								if( $sent_mail ){
									$response['isOtpSend'] = true;
									$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));

									$encryptSwitchType = base64_encode( md5('Google_2FA_Switch') );
									$activeType = base64_encode( md5('EmailOtp') );

									set_transient($clientResendKey, '1', 60);
									ob_start();
									?>
									<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
									<input type="hidden" name="activetype" value="<?php echo $activeType; ?>"  />
									<div class="otp_section pb-3">
										<label for="user_email"><?php echo __('Please enter the OTP', 'corsair-login'); ?></label>
										<input type="text" name="user_otp" id="user_otp" class="input" maxlength="6" pattern="{0-9}+" />
										<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
									</div>
									<input type="submit" name="wpa-submit-verify" id="wpa-submit-verify" class="btn btn-primary" value="<?php echo __('Verify OTP', 'corsair-login'); ?>" />
									<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).' s' : 'Resend OTP' ?></a>
									<script>
										jQuery(document).ready(function($){
											var is_countdown_resend = $('body').find('#resend').attr('data-stat') == 'countdown';
											if(is_countdown_resend){
												var sec = '<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>';
												var countdown = setInterval(() => {
													if(sec > 0){
														sec--;
														$('#resend').text("Resend in "+(sec)+' s')
													}else{
														$('#resend').attr('data-stat','').removeClass('disabled').text('Resend OTP')
														clearInterval(countdown)
													}
												}, 1000);
											}
										});
									</script>
									<?php
									if( $isLoginType['switch'] === true ){
										?><div class="switch-section"><a href="javascript:void(0);" class="switch-method" data-type="<?php echo $encryptSwitchType; ?>"><?php echo __('Switch to another verification method', 'corsair-login'); ?></a></div><?php
									}
									$otpContent = ob_get_clean();
									$response['otpContent'] = $otpContent;
								}else{
									$response['errorMessage'] = __('There was a problem sending OTP to your email. Please try again or contact an admin.', 'corsair-login');
								}
							}else if( isset( $_POST['user_otp'] ) ){
								$user_otp = get_user_meta( $user_id, 'user_otp', true );
								$user_otp_expiration = get_user_meta( $user_id, 'user_otp_expiration', true );
								if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
									$credentials = array();
									$credentials['user_login'] = $user_email;
									$credentials['user_password'] = $user_password;
									$credentials['remember'] = $remember;

									$user_signon = wp_signon( $credentials, true );
									$response['user_signon'] = $user_signon;
									if( is_wp_error($user_signon) ){
										$response['errorMessage'] = $user_signon->get_error_message();
									}else{
										wp_set_auth_cookie( $user_signon->ID, true );
										wp_set_current_user( $user_signon->ID );
										$response['isLoggedIn'] = true;
										$_SESSION['refAccount']=$user_signon->data->user_email;

										add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
										add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
										add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

										$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
										$siteUrl = get_bloginfo('url');
										$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
										$subject = sprintf(__("Login to %s", 'corsair-login'), $blogname);
										$geolocation= getUserGeolocation();
										$browser= getUserBrowser();

										$message = sprintf(__('<h2>Dear member,</h2>
											<p>We noticed a new sign-in to your %s account:</p>
											<p>
												- When: %s <br/>
												- IP: %s <br/>
												- Machine type: %s <br/>
												- Location: %s, %s, %s <br/>
												- Browser: %s
											</p><br/>
											<p>If this was you, you don\'t need to do anything.</p>
											<p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/>
											<p>This is an automated message, please do not reply.</p>
											<p>Best regards,<br/>
											<a href="%s">%s</a> powered by Amplivo Limited</p>',
											'corsair-login'),
											$siteUrlName,
											date_i18n('F d, Y, H:i:s A'),
											corsairlogin_client_ip(),
											$userDevice,
											$geolocation['city'],
											$geolocation['region'],
											$geolocation['country'],
											$browser['name'],
											get_permalink(get_page_by_path('request-reset-link')),
											get_permalink(158),
											$siteUrl,
											$siteUrlName
										);

										// $message = sprintf(__('<h2>Dear member,</h2><p>We noticed a new sign-in to your %s account:</p> <p> -When: %s <br/> -IP: %s</p><br/> <p>If this was you, you don\'t need to do anything.</p><p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), $siteUrlName, date_i18n( 'F d, Y, H:i:s A' ) . ' GMT', corsairlogin_client_ip(), get_permalink( get_page_by_path( 'request-reset-link' ) ), get_permalink( 158 ), $siteUrl, $siteUrlName );

										$htmlContent = mailTemplateHtmlRender( $message );

										if( get_email_send_toggle('login') == 1 ){
											$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
										}

										$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $user_signon->data->user_email ."'");
										if( !( $getKycData ) || ( $getKycData->status != 'approved' && $getKycData->status != 'pending' ) ){
											if( get_email_send_toggle('complete_your_kyc') == 1 ){
												$isSendKycNotification = is_send_kyc_notification( $user_signon->ID );
												if( $isSendKycNotification ){
													$subject = sprintf(__("%s - Complete Your KYC", 'corsair-login'), $blogname);
													$message = sprintf(__('<h2>Dear member,</h2><h3>You need to complete your KYC.</h3><p>You can complete your KYC via this link: <a href="%s">%s</a></p><br/><p>This is automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );

													$htmlContent = mailTemplateHtmlRender( $message );
													$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
												}
											}
										}

									}
								}else{
									$response['errorMessage'] = __('Expired or invalid OTP', 'corsair-login');
								}

							}
						}else if( $isLoginType['status'] == true && $isLoginType['type'] == '2fa' ){
							if( !isset( $_POST['user_otp'] ) ){ //send OTP to user email
								$response['isOtpSend'] = true;
								$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));
								$encryptSwitchType = base64_encode( md5('Email_OTP_Switch') );
								$activeType = base64_encode( md5('GoogleAuth2FA') );
								ob_start();
								?>
								<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>" />
								<input type="hidden" name="activetype" value="<?php echo $activeType; ?>" />
								<div class="otp_section pb-3">
									<label for="user_otp"><?php echo __('Please enter authenticator code', 'corsair-login'); ?></label>
									<input type="text" name="user_otp" id="user_otp" class="input" 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>
								<input type="submit" name="wpa-submit-verify" id="wpa-submit-verify" class="button-primary" value="<?php echo __('Verify Code', 'corsair-login'); ?>" />
								<?php
								if( $isLoginType['switch'] === true ){
								?><div class="switch-section"><a href="javascript:void(0);" class="switch-method" data-type="<?php echo $encryptSwitchType; ?>"><?php echo __('Switch to another verification method', 'corsair-login'); ?></a></div><?php
								}
								$otpContent = ob_get_clean();
								$response['otpContent'] = $otpContent;
							}else if( isset( $_POST['user_otp'] ) ){
								$user_id = $user->ID;

								$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
								$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
								if( $decryptedUserId == $user_id ){
									$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
									if( !empty( $_POST['user_otp'] ) ){
										$google2fa = new \PragmaRX\Google2FA\Google2FA();
										if( $google2fa->verifyKey($google_auth_key, $_POST['user_otp'], 0) ){

											$credentials = array();
											$credentials['user_login'] = $user_email;
											$credentials['user_password'] = $user_password;
											$credentials['remember'] = $remember;

											$user_signon = wp_signon( $credentials, true );
											$response['user_signon'] = $user_signon;
											if( is_wp_error($user_signon) ){
												$response['errorMessage'] = $user_signon->get_error_message();
											}else{
												wp_set_auth_cookie( $user_signon->ID, true );
												wp_set_current_user( $user_signon->ID );
												$response['isLoggedIn'] = true;

												if( in_array( 'supportmanager', $user_signon->roles ) || in_array( 'supportagent', $user_signon->roles ) ){ //only for SA & SM
													$_SESSION['refAccount']=$user_signon->data->user_email;
												}
												if( in_array( 'member', $user_signon->roles ) ){ //only for member
													$_SESSION['refAccount']=$user_signon->data->user_email;

													add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
													add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
													add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

													$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
													$siteUrl = get_bloginfo('url');
													$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
													$subject = sprintf(__("Login to %s", 'corsair-login'), $blogname);
													$geolocation= getUserGeolocation();
													$browser= getUserBrowser();

													$message = sprintf(__('<h2>Dear member,</h2>
														<p>We noticed a new sign-in to your %s account:</p>
														<p>
															- When: %s <br/>
															- IP: %s <br/>
															- Machine type: %s <br/>
															- Location: %s, %s, %s <br/>
															- Browser: %s
														</p><br/>
														<p>If this was you, you don\'t need to do anything.</p>
														<p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/>
														<p>This is an automated message, please do not reply.</p>
														<p>Best regards,<br/>
														<a href="%s">%s</a> powered by Amplivo Limited</p>',
														'corsair-login'),
														$siteUrlName,
														date_i18n('F d, Y, H:i:s A'),
														corsairlogin_client_ip(),
														$userDevice,
														$geolocation['city'],
														$geolocation['region'],
														$geolocation['country'],
														$browser['name'],
														get_permalink(get_page_by_path('request-reset-link')),
														get_permalink(158),
														$siteUrl,
														$siteUrlName
													);


													// $message = sprintf(__('<h2>Dear member,</h2><p>We noticed a new sign-in to your %s account:</p> <p> -When: %s <br/> -IP: %s</p><br/> <p>If this was you, you don\'t need to do anything.</p><p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), $siteUrlName, date_i18n( 'F d, Y, H:i:s A' ) . ' GMT', corsairlogin_client_ip(), get_permalink( get_page_by_path( 'request-reset-link' ) ), get_permalink( 158 ), $siteUrl, $siteUrlName );

													$htmlContent = mailTemplateHtmlRender( $message );

													if( get_email_send_toggle('login') == 1 ){
														$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
													}

													$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $user_signon->data->user_email ."'");
													if( !( $getKycData ) || ( $getKycData->status != 'approved' && $getKycData->status != 'pending' ) ){
														if( get_email_send_toggle('complete_your_kyc') == 1 ){
															$isSendKycNotification = is_send_kyc_notification( $user_signon->ID );
															if( $isSendKycNotification ){
																$subject = sprintf(__("Complete Your KYC - %s", 'corsair-login'), $blogname);
																$message = sprintf(__('<h2>Dear member,</h2><h3>You need to complete your KYC.</h3><p>You can complete your KYC via this link: <a href="%s">%s</a></p><br/><p>This is automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );

																$htmlContent = mailTemplateHtmlRender( $message );

																$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
															}
														}
													}
												}

											}

										}else{
											$response['errorMessage'] = __('Invalid authenticator code', 'corsair-login');
										}
									}else{
										$response['errorMessage'] = __('Please enter authenticator code', 'corsair-login');
									}
								}else{
									$response['errorMessage'] = __('User authentication failed. Please try again or contact an admin', 'corsair-login');
								}

							}
						}// Login Security MFP
						else if( $send_mfp_otp_email == 'yes'){
                            // Login Security MFP
								// Will send MFP otp

							$mfp_user_otp = sprintf("%'.06d",mt_rand(0,999999));
							$mfp_user_otp_expiration = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +30 mins"));
							$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
							update_user_meta( $user_id, 'mfp_email_user_otp', $mfp_user_otp );

							$siteUrl = get_bloginfo('url');
							$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

							add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
							add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
							add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

							update_user_meta( $user_id, 'mfp_email_user_otp_expiration', $mfp_user_otp_expiration );
							$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);

							$machine_type = $device_type.' ('. $os.')';
                            $message = sprintf(
                                __('<h2>Dear member,</h2>
                                    <p>We noticed a new sign-in to your %s account:</p>
                                    <p>
                                        - When: %s <br/>
                                        - IP: %s <br/>
                                        - Machine type: %s <br/>
                                        - Location: %s, %s, %s <br/>
                                        - Browser: %s
                                    </p><br/>
                                    <p>Here is your OTP (One-Time Passcode) to login:</p>
                                    <h3><b>%s</b></h3><br/>
                                    <p>If this was you, you don’t need to take any further action.</p>
                                    <p>If you did not generate this activity, we strongly recommend that you immediately <a href="%s">reset your password</a> and <a href="%s">contact our support team</a>.</p><br/>
                                    <p>This is an automated message; please do not reply.</p>
                                    <p>Best regards,<br/>
                                    <a href="%s">%s</a> powered by Amplivo Limited</p>',
                                'corsair-login'),
                                $siteUrlName,
                                date_i18n('F d, Y, H:i:s A'),
                                $ipAddress,
                                $machine_type,
                                $geolocation['city'],
                                $geolocation['region'],
                                $geolocation['country'],
                                $user_info->browser_name,
                                $mfp_user_otp,
                                get_permalink(get_page_by_path('request-reset-link')),
                                get_permalink(158),
                                $siteUrl,
                                $siteUrlName
                            );

							$htmlContent = mailTemplateHtmlRender( $message );

							$sent_mail = wp_mail( $user->user_email, $subject, $htmlContent );

							if( $sent_mail ){
								$response['isMfpOtpSend'] = true;
								$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));
								$activeType = base64_encode( md5('EmailMfpOtp') );

								set_transient($clientResendKey, '1', 60);
								ob_start();
								// Query to check if the user ID exists in the table.
								global $wpdb;
								$userInfoTable = $wpdb->prefix . 'user_login_info';
								$user_id_to_check = $user->ID;
								$user_exists = $wpdb->get_var(
									$wpdb->prepare(
										"SELECT COUNT(*) FROM $userInfoTable WHERE user_id = %d",
										$user_id_to_check
									)
								);
								?>
								<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
								<input type="hidden" name="activetype" value="<?php echo $activeType; ?>"  />
								<div class="otp_section pb-3">
									<?php

									if ($user_exists > 0) {
										?>
										<h5 class="mfp_display_text"><?php echo __('We noticed a sign-in from a device you don’t usually use. To help keep your account safe, please verify it’s you.', 'corsair-login'); ?></h5>

									<?php } else {
										?>
										<h5 class="mfp_display_text"><?php echo __('To help keep your account safe, please verify it’s you.', 'corsair-login'); ?></h5>


									<?php } ?>

									<label for="user_email"><?php echo __('Please enter the OTP', 'corsair-login'); ?></label>
									<input type="text" name="user_mfp_otp" id="user_mfp_otp" class="input" maxlength="6" pattern="{0-9}+" />
									<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
								</div>
								<input type="submit" name="wpa-submit-verify" id="wpa-submit-verify" class="btn btn-primary" value="<?php echo __('Verify OTP', 'corsair-login'); ?>" />
								<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resendMfp" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).'s' : 'Resend OTP' ?></a>
								<script>
									jQuery(document).ready(function($){
										var is_countdown_resend = $('body').find('#resendMfp').attr('data-stat') == 'countdown';
										if(is_countdown_resend){
											var sec = '<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>';
											var countdown = setInterval(() => {
												if(sec > 0){
													sec--;
													$('#resendMfp').text("Resend in "+(sec)+'s')
												}else{
													$('#resendMfp').attr('data-stat','').removeClass('disabled').text('Resend OTP')
													clearInterval(countdown)
												}
											}, 1000);
										}
									});
								</script>
								<?php
								$mfpOtpContent = ob_get_clean();
								$response['mfpOtpContent'] = $mfpOtpContent;
							}else{
								$response['errorMessage'] = __('There was a problem sending OTP to your email. Please try again or contact an admin.', 'corsair-login');
							}
                            // Login Security MFP END
						}else if(isset( $_POST['resendMfpOtpAct'] ) && $_POST['resendMfpOtpAct'] == 1){
							// Login Security MFP
								//Resend MFP otp mail
							if ((get_transient($clientResendKey) !== false)) {
								$response['errorMessage'] = __('You can resend OTP after timer reset', 'corsair-login');
							}else{
								$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
								$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
								if( $decryptedUserId == $user_id ){
									$user_mfp_resend_otp = sprintf("%'.06d",mt_rand(0,999999));
									$user_mfp_resend_otp_expiration = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +30 mins"));
									$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
									update_user_meta( $user_id, 'mfp_email_user_otp', $user_mfp_resend_otp );
									update_user_meta( $user_id, 'mfp_email_user_otp_expiration', $user_mfp_resend_otp_expiration );

									$siteUrl = get_bloginfo('url');
									$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

									add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
									add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
									add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

									$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);

									$machine_type_resend = $_POST['device_type'].' ('.$_POST['os'].')';

                                    $message = sprintf(
                                        __('<h2>Dear member,</h2>
                                            <p>We noticed a new sign-in to your %s account:</p>
                                            <p>
                                                - When: %s <br/>
                                                - IP: %s <br/>
                                                - Machine type: %s <br/>
                                                - Location: %s, %s, %s <br/>
                                                - Browser: %s
                                            </p><br/>
                                            <p>Here is your OTP (One-Time Passcode) to login:</p>
                                            <h3><b>%s</b></h3><br/>
                                            <p>If this was you, you don’t need to take any further action.</p>
                                            <p>If you did not generate this activity, we strongly recommend that you immediately <a href="%s">reset your password</a> and <a href="%s">contact our support team</a>.</p><br/>
                                            <p>This is an automated message; please do not reply.</p>
                                            <p>Best regards,<br/>
                                            <a href="%s">%s</a> powered by Amplivo Limited</p>',
                                        'corsair-login'),
                                        $siteUrlName,
                                        date_i18n('F d, Y, H:i:s A'),
                                        $ipAddress,
                                        $machine_type_resend,
                                        $geolocation['city'],
                                        $geolocation['region'],
                                        $geolocation['country'],
                                        $browser_name,
                                        $user_mfp_resend_otp,
                                        get_permalink(get_page_by_path('request-reset-link')),
                                        get_permalink(158),
                                        $siteUrl,
                                        $siteUrlName
                                    );

									$htmlContent = mailTemplateHtmlRender( $message );
									$sent_mail = wp_mail( $user->user_email, $subject, $htmlContent );
									if( $sent_mail ){
										$response['isMfpOtpSend'] = true;
										$encryptId = base64_encode( $user->ID . md5('CL_RESEND_CL'));

										$encryptSwitchType = base64_encode( md5('Google_2FA_Switch') );
										$activeType = base64_encode( md5('EmailMfpOtp') );

										set_transient($clientResendKey, '1', 60);
										ob_start();
										global $wpdb;
										$userInfoTable = $wpdb->prefix . 'user_login_info';
										$user_id_to_check = $user->ID;
										$user_exists = $wpdb->get_var(
											$wpdb->prepare(
												"SELECT COUNT(*) FROM $userInfoTable WHERE user_id = %d",
												$user_id_to_check
											)
										);
										?>
										<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
										<input type="hidden" name="activetype" value="<?php echo $activeType; ?>"  />
										<div class="otp_section pb-3">
										<?php
										if ($user_exists > 0) { ?>
											<h5 class="mfp_display_text"><?php echo __('We noticed a sign-in from a device you don’t usually use. To help keep your account safe, please verify it’s you.', 'corsair-login'); ?></h5>
										<?php } else { ?>
											<h5 class="mfp_display_text"><?php echo __('To help keep your account safe, please verify it’s you.', 'corsair-login'); ?></h5>
										<?php } ?>
											<label for="user_email"><?php echo __('Please enter the OTP', 'corsair-login'); ?></label>
											<input type="text" name="user_mfp_otp" id="user_mfp_otp" class="input" maxlength="6" pattern="{0-9}+" />
											<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
										</div>
										<input type="submit" name="wpa-submit-verify" id="wpa-submit-verify" class="btn btn-primary" value="<?php echo __('Verify OTP', 'corsair-login'); ?>" />
										<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resendMfp" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).'s' : 'Resend OTP' ?></a>
										<script>
											jQuery(document).ready(function($){
												var is_countdown_resend = $('body').find('#resendMfp').attr('data-stat') == 'countdown';
												if(is_countdown_resend){
													var sec = parseInt('<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>');
													var countdown = setInterval(() => {
														if(sec > 0){
															sec--;
															$('#resendMfp').text("Resend in "+(sec)+'s')
														}else{
															$('#resendMfp').attr('data-stat','').removeClass('disabled').text('Resend OTP')
															clearInterval(countdown)
														}
													}, 1000);
												}
											});
										</script>
										<?php
										$mfpOtpContent = ob_get_clean();
										$response['mfpOtpContent'] = $mfpOtpContent;
									}else{
										$response['errorMessage'] = __('There was a problem sending OTP to your email. Please try again or contact an admin.', 'corsair-login');
									}
								}else{
									$response['errorMessage'] = __('User authentication failed. Please try again or contact an admin', 'corsair-login');
								}
							}
							// Login Security MFP END

						}else if(isset($_POST['user_mfp_otp'])){
							// Login Security MFP
								// MFP login
							$user_mfp_otp = get_user_meta( $user_id, 'mfp_email_user_otp', true );
							$user_mfp_otp_expiration = get_user_meta( $user_id, 'mfp_email_user_otp_expiration', true );
							if( strtotime($user_mfp_otp_expiration) > time() && $user_mfp_otp == $_POST['user_mfp_otp'] ){
								$credentials = array();
								$credentials['user_login'] = $user_email;
								$credentials['user_password'] = $user_password;
								$credentials['remember'] = $remember;

								$user_signon = wp_signon( $credentials, true );
								$response['user_signon'] = $user_signon;
								if( is_wp_error($user_signon) ){
									$response['errorMessage'] = $user_signon->get_error_message();
								}else{
									wp_set_auth_cookie( $user_signon->ID, true );
									wp_set_current_user( $user_signon->ID );
									$response['isLoggedIn'] = true;

									global $wpdb;
									$userInfoTable = $wpdb->prefix.'user_login_info';

									$current_user = wp_get_current_user();
									$user_id =  $current_user->ID;
									$user_email = $current_user->user_email;
									$current_time = current_time('mysql');
									$device_id = $_COOKIE['device_id'];

									$device_exists = $wpdb->get_var(
										$wpdb->prepare(
											"SELECT COUNT(*) FROM $userInfoTable WHERE device_id = %s",
											$device_id
										)
									);
									if($device_exists > 0){
										//update MFP

										$userInfoTable = $wpdb->prefix.'user_login_info';
										$current_user = wp_get_current_user();
										$user_id =  $current_user->ID;
										$user_email = $current_user->user_email;
										$current_time = current_time('mysql');
										$id = $results[0]->id;

										$oldData = $wpdb->get_row(
											$wpdb->prepare("SELECT * FROM $userInfoTable WHERE device_id = %s", $device_id),
											ARRAY_A
										);

										if (isset($_COOKIE['device_id'])) {
											setcookie('device_id', '', time() - 3600, "/");
											unset($_COOKIE['device_id']);
										}
										$new_device_id = uniqid('', true);
										setcookie('device_id', $new_device_id, time() + (10 * 365 * 24 * 60 * 60), "/");

										$userInfoData = [
											'user_id'             => $user_id,
											'ip'                  => $ip,
											'geo_location'        => $geo_location,
											'device_id'        	  => $new_device_id,
											'os'                  => $os,
											'os_version'          => $os_version,
											'device_type'         => $device_type,
											'language'            => $language,
											'browser_name'        => $browser_name,
											'browser_version'     => $browser_version,
											'user_agent'          => $user_agent,
											'local_timezone'      => $local_timezone,
											'cookies_enabled'     => $cookies_enabled,
											'javascript_enabled'  => $javascript_enabled,
											'do_not_track_setting'=> $do_not_track_setting,
											'date'                => $current_time,
										];

										// Where condition
										$where = ['id' => $id];
										// Formats for columns
										$format = [
											'%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',
											'%s', '%s', '%d', '%d', '%d', '%s'
										];
										$where_format = [ '%d' ];
										// Update the record
										$updated_rows = $wpdb->update(
											$userInfoTable,  // Table name
											$userInfoData,   // Data to update
											$where,          // Where clause
											$format,         // Formats for data
											$where_format    // Formats for where clause
										);
										// Check if the update was successful
										if ($updated_rows !== false) {
											$log = [];
											foreach ($userInfoData as $key => $newValue) {
												$oldValue = $oldData[$key] ?? null;
												if ($oldValue != $newValue) {
													$log[] = [
														'field'      => $key,
														'old_value'  => $oldValue,
														'new_value'  => $newValue,
													];
												}
											}
											if (!empty($log)) {
												$log_details = sprintf(
													'%s MFP data updated %s',
													$user_email,
													json_encode($log)
												);
												create_corsairlogin_logs_entry(
													$user_id,
													'MFP data updated',
													'',
													'user',
													$log_details,
													true
												);
											}

										}
									}else{
										$device_id = uniqid('', true); // Generate a unique ID
										setcookie('device_id', $device_id, time() + (10 * 365 * 24 * 60 * 60), "/"); // Set cookie for 10 years
										//insert MFP
										$userInfoData = [
											'user_id'	=>	$user_id,
											'ip'	=>	$ip,
											'geo_location'	=>	$geo_location,
											'device_id'	=>	$device_id,
											'os'	=>	$os,
											'os_version'	=>	$os_version,
											'device_type'	=>	$device_type,
											'language'	=>	$language,
											'browser_name'	=>	$browser_name,
											'browser_version'	=>	$browser_version,
											'user_agent'	=>	$user_agent,
											'local_timezone'	=>	$local_timezone,
											'cookies_enabled'	=>	$cookies_enabled,
											'javascript_enabled'	=>	$javascript_enabled,
											'do_not_track_setting'	=>$do_not_track_setting,
											'date'	=>$current_time,

										];
										$insertingUserInfo = $wpdb->insert( $userInfoTable, $userInfoData );
										if ($insertingUserInfo !== false) {

											$log_details = $user_email . ' MFP data inserted ' . json_encode(array_map(function ($key, $value) {
												return [
													'field' => $key,
													'value' => $value,
												];
											}, array_keys($userInfoData), $userInfoData), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

											create_corsairlogin_logs_entry(
												$user_id,
												'MFP data inserted',
												'',
												'user',
												$log_details,
												true
											);
										}

									}

									$response['mfpLogin'] = true;
									$_SESSION['refAccount']=$user_signon->data->user_email;

									add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
									add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
									add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

									$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
									$siteUrl = get_bloginfo('url');
									$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
									$subject = sprintf(__("Login to %s", 'corsair-login'), $blogname);
									$machine_type = $device_type.' ('. $os.')';

									$message = sprintf(__('<h2>Dear member,</h2>
									<p>We noticed a new sign-in to your %s account:</p>
									<p>
										- When: %s <br/>
										- IP: %s <br/>
										- Machine type: %s <br/>
										- Location: %s, %s, %s <br/>
										- Browser: %s
									</p><br/>
									<p>If this was you, you don\'t need to do anything.</p>
									<p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/>
									<p>This is an automated message, please do not reply.</p>
									<p>Best regards,<br/>
									<a href="%s">%s</a> powered by Amplivo Limited</p>',
									'corsair-login'),
									$siteUrlName,
									date_i18n('F d, Y, H:i:s A'),
									corsairlogin_client_ip(),
									$machine_type,
									$geolocation['city'],
									$geolocation['region'],
									$geolocation['country'],
									$user_info->browser_name,
									get_permalink(get_page_by_path('request-reset-link')),
									get_permalink(158),
									$siteUrl,
									$siteUrlName
								);

									$htmlContent = mailTemplateHtmlRender( $message );
									if( get_email_send_toggle('login') == 1 ){
										$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
									}

								}
							}else{
								$response['errorMessage'] = __('Expired or invalid OTP', 'corsair-login');
							}
								// Login Security MFP END
						}
						// Login Security MFP END
						else{
							$credentials = array();
							$credentials['user_login'] = $user_email;
							$credentials['user_password'] = $user_password;
							$credentials['remember'] = $remember;

							$vpnapi_geolocation = $_SESSION['vpnapi_geolocation'];
							if( isset( $_SESSION['vpnapi_geolocation'] ) && !empty( $vpnapi_geolocation ) ){
								$geolocation= $vpnapi_geolocation;
							}else{
								$geolocation= getUserGeolocation();
							}

							$user_signon = wp_signon( $credentials, true );
							$response['user_signon'] = $user_signon;
							if( is_wp_error($user_signon) ){
								$response['errorMessage'] = $user_signon->get_error_message();
							}else{
								wp_set_auth_cookie( $user_signon->ID, true );
								wp_set_current_user( $user_signon->ID );
								$response['isLoggedIn'] = true;

								// Login Security MFP
								//only update MFP record on every login
								if($update_userInfo == 'yes'){
									global $wpdb;
									$userInfoTable = $wpdb->prefix.'user_login_info';
									$current_user = wp_get_current_user();
									$user_id =  $current_user->ID;
									$user_email = $current_user->user_email;
									$current_time = current_time('mysql');
									$id = $results[0]->id;
									$device_id = $_COOKIE['device_id'];

									$oldData = $wpdb->get_row(
										$wpdb->prepare("SELECT * FROM $userInfoTable WHERE id = %d", $id),
										ARRAY_A
									);

									if (isset($_COOKIE['device_id'])) {
										setcookie('device_id', '', time() - 3600, "/");
										unset($_COOKIE['device_id']);
									}
									$new_device_id = uniqid('', true);
									setcookie('device_id', $new_device_id, time() + (10 * 365 * 24 * 60 * 60), "/");

									$userInfoData = [
										'user_id'             => $user_id,
										'ip'                  => $ip,
										'geo_location'        => $geo_location,
										'device_id'        	  => $new_device_id,
										'os'                  => $os,
										'os_version'          => $os_version,
										'device_type'         => $device_type,
										'language'            => $language,
										'browser_name'        => $browser_name,
										'browser_version'     => $browser_version,
										'user_agent'          => $user_agent,
										'local_timezone'      => $local_timezone,
										'cookies_enabled'     => $cookies_enabled,
										'javascript_enabled'  => $javascript_enabled,
										'do_not_track_setting'=> $do_not_track_setting,
										'date'                => $current_time,
									];


									// Where condition
									//$where = $userInfoData;
									$where = ['id' => $id];
									if (empty($device_id)) {
										unset($where['device_id']); // Remove device_id if it's empty
									} else {
										unset($where['ip']); // Remove ip if device_id is present
									}
									$debug_data = [
										'userInfoData' => $userInfoData,
										'where' => $where,
									];

									// Formats for the columns being updated
									$format = [
										'%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',
										'%s', '%s', '%d', '%d', '%d', '%s'
									];

									$where_format = ['%d'];

									// Update the record
									$updated_rows = $wpdb->update(
										$userInfoTable,  // Table name
										$userInfoData,   // Data to update
										$where,          // WHERE clause
										$format,         // Formats for updated data
										$where_format    // Formats for WHERE clause
									);

									// Check if the update was successful
									if ($updated_rows !== false) {

										$log = [];

										foreach ($userInfoData as $key => $newValue) {
											$oldValue = $oldData[$key] ?? null;
											if ($oldValue != $newValue) {
												$log[] = [
													'field'      => $key,
													'old_value'  => $oldValue,
													'new_value'  => $newValue,
												];
											}
										}
										if (!empty($log)) {
											$log_details = sprintf(
												'%s MFP data updated %s',
												$user_email,
												json_encode($log)
											);
											create_corsairlogin_logs_entry(
												$user_id,               // User ID
												'MFP data updated',     // Log type
												'',                     // Extra value
												'user',                 // User type
												$log_details,           // Logs (changes)
												true                    // islog
											);
										}

									}
								}
								// Login Security MFP ENDDDD

								$dontShow = get_user_meta( $user_signon->ID, 'dont_show_2fa_profile_popup', true );
								if( $dontShow ){
									$response['infoMessage'] = '';
								}else{
									$response['infoMessage'] = __('<b>Logged In</b><br/><br/>You have not set up 2FA login.<br/><br/>You can enable 2FA login under "My Profile" page.', 'corsair-login');
								}

								if( in_array( 'supportmanager', $user_signon->roles ) || in_array( 'supportagent', $user_signon->roles ) ){
									$response['infoMessage'] = '';
								}

								if( in_array( 'supportmanager', $user_signon->roles ) || in_array( 'supportagent', $user_signon->roles ) ){ //only for SA & SM
									$_SESSION['refAccount']=$user_signon->data->user_email;
								}

								if( in_array( 'member', $user_signon->roles ) ){ //only for member
									$_SESSION['refAccount']=$user_signon->data->user_email;

									add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
									add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
									add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

									$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
									$siteUrl = get_bloginfo('url');
									$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
									$subject = sprintf(__("Login to %s", 'corsair-login'), $blogname);
									
									$browser= getUserBrowser();

									$message = sprintf(__('<h2>Dear member,</h2>
										<p>We noticed a new sign-in to your %s account:</p>
										<p>
											- When: %s <br/>
											- IP: %s <br/>
											- Machine type: %s <br/>
											- Location: %s, %s, %s <br/>
											- Browser: %s
										</p><br/>
										<p>If this was you, you don\'t need to do anything.</p>
										<p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/>
										<p>This is an automated message, please do not reply.</p>
										<p>Best regards,<br/>
										<a href="%s">%s</a> powered by Amplivo Limited</p>',
										'corsair-login'),
										$siteUrlName,
										date_i18n('F d, Y, H:i:s A'),
										corsairlogin_client_ip(),
										$userDevice,
										$geolocation['city'],
										$geolocation['region'],
										$geolocation['country'],
										$browser['name'],
										get_permalink(get_page_by_path('request-reset-link')),
										get_permalink(158),
										$siteUrl,
										$siteUrlName
									);

									// $message = sprintf(__('<h2>Dear member,</h2><p>We noticed a new sign-in to your %s account:</p> <p> -When: %s <br/> -IP: %s</p><br/> <p>If this was you, you don\'t need to do anything.</p><p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), $siteUrlName, date_i18n( 'F d, Y, H:i:s A' ) . ' GMT', corsairlogin_client_ip(), get_permalink( get_page_by_path( 'request-reset-link' ) ), get_permalink( 158 ), $siteUrl, $siteUrlName );

									$htmlContent = mailTemplateHtmlRender( $message );

									if( get_email_send_toggle('login') == 1 ){
										$sent_mail = wp_mail( $user->user_email, $subject, $htmlContent );

									}

									$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $user_signon->data->user_email ."'");
									if( !( $getKycData ) || ( $getKycData->status != 'approved' && $getKycData->status != 'pending' ) ){
										if( get_email_send_toggle('complete_your_kyc') == 1 ){
											$isSendKycNotification = is_send_kyc_notification( $user_signon->ID );
											if( $isSendKycNotification ){
												$subject = sprintf(__("%s - Complete Your KYC", 'corsair-login'), $blogname);
												$message = sprintf(__('<h2>Dear member,</h2><h3>You need to complete your KYC.</h3><p>You can complete your KYC via this link: <a href="%s">%s</a></p><br/><p>This is automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );

												$htmlContent = mailTemplateHtmlRender( $message );

												$sent_mail = wp_mail( $user_signon->data->user_email, $subject, $htmlContent );
											}
										}
									}
								}


							}
						}

					}
				}else{
					$response['errorMessage'] = $user->get_error_message();
				}

			}
		}
		if (!empty($response['errorMessage'])) {
			set_transient($client_key, '1', 2);
		}
	}else{
		$response['errorMessage'] = __('Something went wrong. Please try again.');
	}
	wp_send_json(
		$response,
		$status_code
	);
}
function mailTemplateHtmlRender( $message ){

	$htmlurl = CLOG_PLUGIN_URL.'mail_template.html';
	$htmlContent = file_get_contents($htmlurl);
	$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 © CSRnow.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: Google Sans,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);
	return $htmlContent;
}
add_action('wp_ajax_nopriv_corsair_user_reset_password', 'corsair_login_try_to_reset_request_action');
function corsair_login_try_to_reset_request_action(){
	if (empty($client_ip_address = corsairlogin_client_ip())) {
		die();
	}
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$client_key = 'reset_request_attempt_' . $client_ip_address;
	$status_code = 200;
	$response = array(
		'isResetRequested' => false,
		'errorMessage' => '',
	);
	if( wp_verify_nonce( $_POST['micro_nonce'],'corsair_reset_password_request' ) ){
		if ((get_transient($client_key) !== false)) {
			$response['errorMessage'] = 'Slow down a bit';
		} elseif (empty($user_email = sanitize_text_field($_POST['user_email']))) {
			$response['errorMessage'] = 'No email';
		} elseif( !filter_var($user_email, FILTER_VALIDATE_EMAIL) ){
			$response['errorMessage'] = 'Invalid email';
		}elseif( !email_exists( $user_email ) ){

			$user_email = $_POST['user_email'];
			$getTokenHolderData = $wpdb->get_row("SELECT `email`,`username`,`first_name`,`last_name` FROM $tableTokenHolder WHERE 1 AND `email`='". $user_email ."' AND `email` <> '' AND `email` IS NOT NULL ORDER BY `id` DESC LIMIT 1");

			if( $getTokenHolderData ){ //check in token holder data
				if( !empty( $getTokenHolderData->email ) && !empty( $getTokenHolderData->username ) ){
					$user_email = $getTokenHolderData->email;
					$username = $getTokenHolderData->username;
					$user_password = wp_generate_password( 12, false );
					$user = wp_create_user( $username, $user_password, $user_email );
					if( !is_wp_error($user) ){
						$user = get_user_by( 'email', $user_email );
						if( $user instanceof WP_User ) {
							$user->add_role( 'member' );
							$user->remove_role( 'subscriber' );
							$user_id = $user->ID;
							$user_info = get_userdata($user_id);

							update_user_meta( $user_id, 'csrnow_login_enable', 1 );

							$unique = get_password_reset_key( $user_info );
							$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');
							$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
							$siteUrl = get_bloginfo('url');
							$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

							add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
							add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
							add_filter('wp_mail_content_type', function(){ return "text/html"; } );
							$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

							$unique_url_txt = disable_email_link( $unique_url );

							$message = sprintf(__('<br><p>This is an e-mail from %s.</p> <p> You are receiving this email because we received a password reset request for your account.</p><br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );

							$htmlContent = mailTemplateHtmlRender( $message );

							$sent_mail = wp_mail( $user_email, $subject, $htmlContent );
							if ( !$sent_mail ){
								$response['errorMessage'] = __('There was a problem sending you email. Please try again or contact an admin.', 'corsair-login');
							}else{
								$response['errorMessage'] = sprintf( __('To increase account security, you are required to set a password on %s.<br/><br/>We have sent you link to set the password.', 'corsair-login'), $siteUrlName );
								$response['isResetRequested'] = true;

								//cip_logs
								$logs = sprintf( __('%s registered & password reset sent at %s (reset password page - tokenholder)', 'corsair-login'), $user_info->user_email, date_i18n('d/m/Y H:i A') );
								create_corsairlogin_logs_entry( $user_info->ID, 'profile', '','member', $logs, true  );
							}

						}else{
							$response['errorMessage'] = __('Something went wrong. Please try again.');
						}
					}else{
						$response['errorMessage'] = $user->get_error_message();
					}

				}else{
					$response['errorMessage'] = 'Email address or username not found.<br/>Use your Amplivo email to register.';
				}
			}else{

				$foundUser = corsair_get_users_from_sourceapi_data( $user_email );

				if( $foundUser['result'] ){
					$user_password = wp_generate_password( 12, false );
					$user = wp_create_user( $foundUser['Username'], $user_password, $user_email );
					if( !is_wp_error($user) ){
						$user = get_user_by( 'email', $user_email );
						if( $user instanceof WP_User ) {
							$user->add_role( 'member' );
							$user->remove_role( 'subscriber' );
							$user_id = $user->ID;
							$user_info = get_userdata($user_id);

							update_user_meta( $user_id, 'csrnow_login_enable', 1 );
							update_user_meta( $user_id, 'first_name', trim( $foundUser['first_name'] ) );
                            update_user_meta( $user_id, 'last_name', trim( $foundUser['last_name'] ) );

							$unique = get_password_reset_key( $user_info );
							$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');
							$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
							$siteUrl = get_bloginfo('url');
							$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

							add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
							add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
							add_filter('wp_mail_content_type', function(){ return "text/html"; } );
							$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

							$unique_url_txt = disable_email_link( $unique_url );

							$message = sprintf(__('<br><p>This is an e-mail from %s.</p> <p> You are receiving this email because we received a password reset request for your account.</p><br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );

							$htmlContent = mailTemplateHtmlRender( $message );

							$sent_mail = wp_mail( $user_email, $subject, $htmlContent );
							if ( !$sent_mail ){
								$response['errorMessage'] = __('There was a problem sending you email. Please try again or contact an admin.', 'corsair-login');
							}else{
								$response['errorMessage'] = sprintf( __('To increase account security, you are required to set a password on %s.<br/><br/>We have sent you link to set the password.', 'corsair-login'), $siteUrlName );
								$response['isResetRequested'] = true;

								//cip_logs
								$logs = sprintf( __('%s registered & password reset sent at %s (reset password page - amplivo)', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
								create_corsairlogin_logs_entry( $user->ID, 'profile', '','member', $logs, true  );
							}

						}else{
							$response['errorMessage'] = __('Something went wrong. Please try again.');
						}
					}else{
						$response['errorMessage'] = $user->get_error_message();
					}
				}else{
					$response['errorMessage'] = 'Email address not found.<br/>Use your Amplivo email to register.';
				}
			}

		}else {

			$user = get_user_by( 'email', $user_email );
			if( $user instanceof WP_User ) {
				$user_id = $user->ID;
				$user_info = get_userdata($user_id);
				$unique = get_password_reset_key( $user_info );
				$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');
				$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( __( '%s','corsair-login'), get_option('blogname') ); } );
				add_filter('wp_mail_content_type', function(){ return "text/html"; } );
				$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

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

				$unique_url_txt = disable_email_link( $unique_url );

				$message = sprintf(__('<br><p>This is an e-mail from %s. </p> <p>You are receiving this email because we received a password reset request for your account.</p> <br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );

				$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 © CSRnow.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: Google Sans, 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( $user_email, $subject, $htmlContent );
				if ( !$sent_mail ){
					$response['errorMessage'] = __('There was a problem sending you email. Please try again or contact an admin.', 'corsair-login');
				}else{
					$response['errorMessage'] = __('Password reset link sent.', 'corsair-login');
					$response['isResetRequested'] = true;

					//cip_logs
					$logs = sprintf( __('password reset sent of %s at %s (reset password page)', 'corsair-login'), $user_email, date_i18n('d/m/Y H:i A') );
					create_corsairlogin_logs_entry( $user_info->ID, 'profile', '','member', $logs, true  );
				}

			}else{
				$response['errorMessage'] = __('Something went wrong. Please try again.');
			}

		}
		if (!empty($response['errorMessage'])) {
			set_transient($client_key, '1', 2);
		}
	}else{
		$response['errorMessage'] = __('Something went wrong. Please try again.');
	}
	wp_send_json(
		$response,
		$status_code
	);
}
add_action('wp_ajax_nopriv_corsair_user_reseting_password', 'corsair_login_try_to_reseting_password_action');
function corsair_login_try_to_reseting_password_action(){
	if (empty($client_ip_address = corsairlogin_client_ip())) {
		die();
	}
	$client_key = 'reseting_password_attempt_' . $client_ip_address;
	$status_code = 200;
	$response = array(
		'isReset' => false,
		'isLoggedIn' => false,
		'errorMessage' => '',
	);
	if( wp_verify_nonce( $_POST['micro_nonce'],'corsair_reseting_password' ) ){
		$rp_cookie       = 'wp-resetpass-' . COOKIEHASH;

		$trim_pass1 = $_POST['pass1'] = trim( $_POST['pass1'] );
		$number    = preg_match('@[0-9]@', $_POST['pass1']);
		$pwStrengthError = false;
		$pwStrengthMsg = array();
		$pwStrengthMsg[] = __('<b>Password</b>','corsair-login');
		$errorOne = false;
		$errorTwo = false;
		if( !$number ){
			$pwStrengthMsg[] = __("must contain at least one number.","corsair-login");
			$pwStrengthError = true;
			$errorOne = true;
		}
		if( strlen($_POST['pass1']) < 8 ){
			$pwStrengthMsg[] = __("must be at least 8 characters.","corsair-login");
			$pwStrengthError = true;
			$errorTwo = true;
		}
		if( $errorOne && $errorTwo ){
			$pwStrengthMsg = array();
			$pwStrengthMsg[] = __('<b>Password</b>','corsair-login');
			$pwStrengthMsg[] = __("must contain at least one number and must be at least 8 characters.","corsair-login");
		}
		if( (get_transient($client_key) !== false) ){
			$response['errorMessage'] = 'Slow down a bit';
		} elseif ( empty( $_POST['pass1'] ) ) {
			$response['errorMessage'] = 'The password is required.';
		} elseif( !empty( $_POST['pass1'] ) && empty( $trim_pass1 ) ){
			$response['errorMessage'] = 'The password cannot be a space or all spaces.';
		}elseif ( ! empty( $_POST['pass1'] ) && trim( $_POST['pass2'] ) !== $_POST['pass1'] ) {
			$response['errorMessage'] = 'Passwords don\'t match.';
		}else if( $pwStrengthError ){
			$response['errorMessage'] = implode("<br/>", $pwStrengthMsg );
		}else {

			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 );
				$decryptedLogin = base64_decode( $_POST['user_login'] );
				$user_login = urldecode( preg_replace(sprintf('/%s/', md5('CLRPLOGIN') ), '', $decryptedLogin) );

				if ( isset( $user_login ) && !hash_equals( $rp_login, $user_login ) ) {
					$user = false;
					$response['errorMessage'] = __('Something went wrong. Please try again.');
					wp_send_json(
						$response,
						$status_code
					);
				}

				if ( isset( $_POST['pass1'] ) && ! hash_equals( $rp_key, $_POST['rp_key'] ) ) {
					$user = false;
					$response['errorMessage'] = __('Something went wrong. Please try again.');
					wp_send_json(
						$response,
						$status_code
					);
				}
			} else {
				$user = false;
			}
			if($user){
				if( !is_wp_error($user) ){
					/* $response['errorMessage'] = __('Something went wrong. Please try again. 4');
					$response['user'] = $user;
					$response['pass'] = $_POST['pass1']; */
					reset_password( $user, $_POST['pass1'] );
					$response['isReset'] = true;
					$response['errorMessage'] = __('Password reset successfully');
					$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
					$siteUrl = get_bloginfo('url');
					$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
					add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
					add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
					add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );
					$subject = sprintf(__("%s - Login password changed", 'corsair-login'), $blogname);

					$htmlurl = CLOG_PLUGIN_URL.'mail_template.html';
					$htmlContent = file_get_contents($htmlurl);
					$message = sprintf(__('<br>Dear member,<br/><p>This notice confirms that your login password was changed on <a href="%s">%s</a>.</p><p>If this was you, you don\'t need to do anything.</p><p>If not, please <a href="%s">reset your login password</a> and <a href="%s">contact our support</a> immediately.</p><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'), $siteUrl, $siteUrlName, get_permalink( get_page_by_path( 'request-reset-link' ) ), get_permalink( 158 ), $siteUrl, $siteUrlName );

					$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 © CSRnow.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: Google Sans, 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( $user->user_email, $subject, $htmlContent );
					$cssetautologin = get_user_meta( $user->ID, 'cssetautologin', true );

					$logs = sprintf( __('%s reset their password at %s', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
					create_corsairlogin_logs_entry( $user->ID, 'profile', '','member', $logs, true  );

					if( $cssetautologin ){
						$remember = false;
						$credentials = array();
						$credentials['user_login'] = $user->user_email;
						$credentials['user_password'] = $_POST['pass1'];
						$credentials['remember'] = $remember;

						$user_signon = wp_signon( $credentials, true );
						if( is_wp_error($user_signon) ){
							$response['errorMessage'] = $user_signon->get_error_message();
						}else{
							wp_set_auth_cookie( $user_signon->ID, true );
							wp_set_current_user($user_signon->ID);
							$response['isLoggedIn'] = true;
							$_SESSION['refAccount']=$user_signon->data->user_email;
						}
						delete_user_meta( $user->ID, 'cssetautologin' );
					}
				}else{
					$response['errorMessage'] = __('Something went wrong. Please try again.');
				}
			}else{
				$response['errorMessage'] = __('Something went wrong. Please try again.');
			}

		}
		if (!empty($response['errorMessage'])) {
			set_transient($client_key, '1', 2);
		}
	}else{
		$response['errorMessage'] = __('Something went wrong. Please try again.');
	}
	wp_send_json(
		$response,
		$status_code
	);
}
add_action( 'login_form_rp', 'redirect_to_custom_password_reset' );
add_action( 'login_form_resetpass', 'redirect_to_custom_password_reset' );
function redirect_to_custom_password_reset() {
    if ( 'GET' == $_SERVER['REQUEST_METHOD'] ) {
        // Verify key / login combo
        $user = check_password_reset_key( $_REQUEST['key'], $_REQUEST['login'] );
        if ( ! $user || is_wp_error( $user ) ) {
            if ( $user && $user->get_error_code() === 'expired_key' ) {
                wp_redirect( home_url( 'request-reset-link?error=expiredkey' ) );
            } else {
                wp_redirect( home_url( 'request-reset-link?error=invalidkey' ) );
            }
            exit;
        }
        $redirect_url = home_url( 'reset-password' );
        $redirect_url = add_query_arg( 'login', esc_attr( $_REQUEST['login'] ), $redirect_url );
        $redirect_url = add_query_arg( 'key', esc_attr( $_REQUEST['key'] ), $redirect_url );
        wp_redirect( $redirect_url );
        exit;
    }
}
function get_error_message( $error_code ) {
    switch ( $error_code ) {
        case 'expiredkey':
		case 'invalidkey':
			return __( 'The password reset link you used is not valid anymore.', 'corsair-login' );
		case 'password_reset_mismatch':
			return __( "The two passwords you entered don't match.", 'corsair-login' );

		case 'password_reset_empty':
			return __( "Sorry, we don't accept empty passwords.", 'corsair-login' );
        default:
            break;
    }

    return __( 'An unknown error occurred. Please try again later.', 'corsair-login' );
}
add_action( 'wp_ajax_user_login_auth_option_act', 'corsair_login_user_login_auth_option_act_callback' );
function corsair_login_user_login_auth_option_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_USERS_LogiN_AuthenticatioN_OPTION_' ) && ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$corsair_2fa_otp = get_option( 'corsair_2fa_otp' );
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		if( $_POST['login_auth_type'] == 'otp' ){
			if( $corsair_2fa_otp == 'yes' ){
				update_user_meta( $user_id, 'login_auth_type', $_POST['login_auth_type'] );
			}
		}else if( $_POST['login_auth_type'] == '2fa' ){
			if( $corsair_2fa_ga == 'yes' ){
				update_user_meta( $user_id, 'login_auth_type', $_POST['login_auth_type'] );
			}
		}
		$out = array( "error" => 0,'msg' => __('Option updated.','corsair-login') );
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_googleAuth2FAactivationAct', 'corsair_login_googleAuth2FAactivationAct_callback' );
function corsair_login_googleAuth2FAactivationAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPGoogleAuthenticatorEnablingCIP_' ) && ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;

		if( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'login' || $_POST['thisType'] == 'withdrawal' ) ){
			if( !empty( $_POST['key'] ) && !empty( $_SESSION['google_auth_key'] ) ){
				if( $_POST['key'] == $_SESSION['google_auth_key'] ){
					$google2fa = new \PragmaRX\Google2FA\Google2FA();
					if( $google2fa->verifyKey($_SESSION['google_auth_key'], $_POST['code'], 0) ){
						update_user_meta( $user_id, 'google_auth_key', $_SESSION['google_auth_key'] );
						// delete_user_meta( $user_id, 'otp_auth_key' );
						$_SESSION['google_auth_key'] = "";
						unset( $_SESSION['google_auth_key'] );

						if( $_POST['thisType'] == 'login' ){
							update_user_meta( $user_id, 'google_auth_key_login', 1 );
						}else if( $_POST['thisType'] == 'withdrawal' ){
							update_user_meta( $user_id, 'google_auth_key_withdrawal', 1 );
						}
						$out = array( "error" => 0,'msg' => __('Google authenticator activated.','corsair-login'), 'thisType' => $_POST['thisType'] );

						$logs = sprintf( __('2FA google authenticator activated for %s by %s at %s', 'corsair-login'), $_POST['thisType'], $current_user->user_email, date_i18n('d/m/Y H:i A') );
						create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );
					}else{
						$out = array( "error" => 1,'msg' => __('Invalid backup key or 6-digit code.','corsair-login') );
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Please enter valid backup key to continue.','corsair-login') );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Please enter valid backup key to continue.','corsair-login') );
			}
		}

	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_googleAuth2FADeactivateAct', 'corsair_login_googleAuth2FADeactivateAct_callback' );
function corsair_login_googleAuth2FADeactivateAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPGoogleAuthenticatorDisablingCIP_' ) && ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		if( !empty( $_POST['code'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['code'], 0) ){
				delete_user_meta( $user_id, 'google_auth_key' );
				delete_user_meta( $user_id, 'google_auth_key_login' );
				delete_user_meta( $user_id, 'google_auth_key_withdrawal' );
				$out = array( "error" => 0,'msg' => __('Google authenticator disabled.','corsair-login') );

				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

				$subject = sprintf(__("%s - Google 2FA (disabled)", 'corsair-login'), $blogname);
				$message = sprintf( __('Dear member, <br/><p>Your Google 2FA authentication has been disabled.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrl, $siteUrlName );

				add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
				add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
				add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

				$htmlContent = mailTemplateHtmlRender( $message );

				if( get_email_send_toggle('2fa_enabled_disabled') == 1 ){
					$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
				}

				$logs = sprintf( __('2FA google authenticator disabled by %s at %s', 'corsair-login'), $current_user->user_email, date_i18n('d/m/Y H:i A') );
				create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid 6-digit google authenticator code.','corsair-login') );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter 6-digit google authenticator code.','corsair-login') );
		}
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_sendOtpForActivatingAct', 'corsair_login_sendOtpForActivatingAct_callback' );
function corsair_login_sendOtpForActivatingAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login'), 'html' => '' );
	if (empty($client_ip_address = corsairlogin_client_ip())) {
		wp_send_json($out);
		die();
	}
	// if( wp_verify_nonce( $_POST['_micro'],'_CIPGoogleAuthenticatorEnablingCIP_' ) && ( current_user_can( 'member' ) ) ){
	if( current_user_can( 'member' ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$formHtml = "";
		$clientResendKey = 'resend_enabledisable_attempt_' . $client_ip_address;
		$user_otp = sprintf("%'.06d",mt_rand(0,999999));
		//$user_otp_expiration = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +30 mins"));
		$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));

		if( isset( $_POST['resendOtpAct'] ) && $_POST['resendOtpAct'] == 1 ){
			if ((get_transient($clientResendKey) !== false)) {
				$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset.','corsair-login'), 'html' => '' );
				wp_send_json($out);
				exit;
			}
			$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
			update_user_meta( $user_id, 'user_otp_activate_code', $user_otp );
			// update_user_meta( $user_id, 'user_otp_expiration', $user_otp_expiration );

			add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
			add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
			add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

			$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
			$siteUrl = get_bloginfo('url');
			$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
			$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
			$message = sprintf(__('<h2>You are attempting to activate One-Time-Passcode (OTP) authentication in %s</h2><p>Please insert the Passcode below to activate OTP.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				set_transient($clientResendKey, '1', 60);
				$out = array( "error" => 0,'msg' => __('OTP Sent to your email','corsair-login'), 'html' => '' );
			}else{
				$out = array( "error" => 1,'msg' => __('There was a problem sending you email. Please try again or contact an admin.','corsair-login'), 'html' => $formHtml );
			}

		}else{

			$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
			update_user_meta( $user_id, 'user_otp_activate_code', $user_otp );
			// update_user_meta( $user_id, 'user_otp_expiration', $user_otp_expiration );

			add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
			add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
			add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

			$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
			$siteUrl = get_bloginfo('url');
			$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
			$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
			$message = sprintf(__('<h2>You are attempting to activate One-Time-Passcode (OTP) authentication in %s</h2><p>Please insert the Passcode below to activate OTP.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				set_transient($clientResendKey, '1', 60);
				ob_start();
				?>
				<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="otp2faEnableFrm" class="otp2faEnableFrm">
									<div class="row">
										<div class="col-12">
											<p class="text-center main_heading text-success mb-0"><b><?php _e('One-Time-Passcode has been sent to your email.', 'corsair-login'); ?></b></p>
											<p class="text-center main_heading"><b><?php _e('Activate OTP Authentication', 'corsair-login'); ?></b></p>
											<div class="form-group">
												<label for="verify-code"><?php _e('Please enter the OTP', 'corsair-login'); ?></label>
												<input type="number" class="form-control" name="code" placeholder="" id="verify-code" maxlength="6">
												<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
											</div>
											<input type="submit" name="submit" class="btn action-button" value="<?php _e('Verify', 'corsair-login'); ?>" />
											<input type="button" name="cancel" class="btn action-button" data-dismiss="modal" value="<?php _e('Cancel', 'corsair-login'); ?>" />
											<a class="btn getnewcodeenable disabled" data-stat="countdown" href="javascript:void(0);" id="getnewcode" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).' s' : 'Resend OTP' ?></a>
										</div>
									</div>
									<input type="hidden" name="action" value="otpAuth2FAactivateAct" />
									<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPOTPAuthenticatorActivatingCIP_'); ?>" />
									<p class="resend_response"></p>
								</form>
							</div>
						</div>
					</div>
				</div>
				<script>
					jQuery(document).ready(function($){
						var is_countdown_resend = $('body').find('#getnewcode').attr('data-stat') == 'countdown';
						if(is_countdown_resend){
							var sec = parseInt('<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>');
							var countdown = setInterval(() => {
								if(sec > 0){
									sec--;
									$('#getnewcode').text("Resend in "+(sec)+' s')
								}else{
									$('#getnewcode').attr('data-stat','').removeClass('disabled').text('Resend OTP')
									clearInterval(countdown)
								}
							}, 1000);
						}
					});
				</script>
				<?php
				$formHtml .= ob_get_clean();
				$out = array( "error" => 0,'msg' => __('OTP Sent to your email','corsair-login'), 'html' => $formHtml );
			}else{
				$out = array( "error" => 1,'msg' => __('There was a problem sending you email. Please try again or contact an admin.','corsair-login'), 'html' => $formHtml );
			}
		}

	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_sendOtpForDeActivatingAct', 'corsair_login_sendOtpForDeActivatingAct_callback' );
function corsair_login_sendOtpForDeActivatingAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login'), 'html' => '' );
	if (empty($client_ip_address = corsairlogin_client_ip())) {
		wp_send_json($out);
		die();
	}
	// if( wp_verify_nonce( $_POST['_micro'],'_CIPGoogleAuthenticatorEnablingCIP_' ) && ( current_user_can( 'member' ) ) ){
	if( current_user_can( 'member' ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$formHtml = "";
		$clientResendKey = 'resend_enabledisable_attempt_' . $client_ip_address;
		$user_otp = sprintf("%'.06d",mt_rand(0,999999));

		if( isset( $_POST['resendOtpAct'] ) && $_POST['resendOtpAct'] == 1 ){
			if ((get_transient($clientResendKey) !== false)) {
				$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset.','corsair-login'), 'html' => '' );
				wp_send_json($out);
				exit;
			}

			$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
			update_user_meta( $user_id, 'user_otp_deactivate_code', $user_otp );

			add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
			add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
			add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

			$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
			$siteUrl = get_bloginfo('url');
			$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
			$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
			$message = sprintf(__('<h2>You are attempting to deactivate One-Time-Passcode (OTP) authentication in %s</h2><p>Please insert the Passcode below to deactivate OTP.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				set_transient($clientResendKey, '1', 60);
				$out = array( "error" => 0,'msg' => __('OTP Sent to your email','corsair-login'), 'html' => '' );
			}else{
				$out = array( "error" => 1,'msg' => __('There was a problem sending you email. Please try again or contact an admin.','corsair-login'), 'html' => $formHtml );
			}

		}else{
			$otp_resend_time = date("Y-m-d H:i:s" ,strtotime(date('Y-m-d H:i:s')." +1 min"));
			update_user_meta( $user_id, 'user_otp_deactivate_code', $user_otp );

			add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
			add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
			add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

			$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
			$siteUrl = get_bloginfo('url');
			$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
			$subject = sprintf(__("%s - Email OTP Verification", 'corsair-login'), $blogname);
			$message = sprintf(__('<h2>You are attempting to deactivate One-Time-Passcode (OTP) authentication in %s</h2><p>Please insert the Passcode below to deactivate OTP.</p><h3><b>%s</b></h3><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName );
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				set_transient($clientResendKey, '1', 60);
				ob_start();
				?>
				<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="otp2faDisableFrm" class="otp2faDisableFrm">
									<div class="row">
										<div class="col-12">
											<p class="text-center main_heading text-success mb-0"><b><?php _e('One-Time-Passcode has been sent to your email.', 'corsair-login'); ?></b></p>
											<p class="text-center main_heading"><b><?php _e('Deactivate OTP Authentication', 'corsair-login'); ?></b></p>
											<div class="form-group">
												<label for="verify-code"><?php _e('Please enter the OTP', 'corsair-login'); ?></label>
												<input type="number" class="form-control" name="code" placeholder="" id="verify-code" maxlength="6">
												<small class="form-text text-muted"><?php _e('Enter the 6-digit verification code sent to your email.') ?></small>
											</div>
											<input type="submit" name="submit" class="btn action-button" value="<?php _e('Verify', 'corsair-login'); ?>" />
											<input type="button" name="cancel" class="btn action-button" data-dismiss="modal" value="<?php _e('Cancel', 'corsair-login'); ?>" />
											<a class="btn getnewcodedisable disabled" data-stat="countdown" href="javascript:void(0);" id="getnewcode" disabled><?= time() < strtotime($otp_resend_time) ? 'Resend in '.(strtotime($otp_resend_time) - time()).' s' : 'Resend OTP' ?></a>
										</div>
									</div>
									<input type="hidden" name="action" value="otpAuth2FDeAactivateAct" />
									<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPOTPAuthenticatorDeActivatingCIP_'); ?>" />
									<p class="resend_response"></p>
								</form>
							</div>
						</div>
					</div>
				</div>
				<script>
					jQuery(document).ready(function($){
						var is_countdown_resend = $('body').find('#getnewcode').attr('data-stat') == 'countdown';
						if(is_countdown_resend){
							var sec = parseInt('<?= time() < strtotime($otp_resend_time) ? (strtotime($otp_resend_time) - time()) : 0 ?>');
							var countdown = setInterval(() => {
								if(sec > 0){
									sec--;
									$('#getnewcode').text("Resend in "+(sec)+' s')
								}else{
									$('#getnewcode').attr('data-stat','').removeClass('disabled').text('Resend OTP')
									clearInterval(countdown)
								}
							}, 1000);
						}
					});
				</script>
				<?php
				$formHtml .= ob_get_clean();
				$out = array( "error" => 0,'msg' => __('OTP Sent to your email','corsair-login'), 'html' => $formHtml );
			}else{
				$out = array( "error" => 1,'msg' => __('There was a problem sending you email. Please try again or contact an admin.','corsair-login'), 'html' => $formHtml );
			}
		}

	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_otpAuth2FAactivateAct', 'corsair_login_otpAuth2FAactivateAct_callback' );
function corsair_login_otpAuth2FAactivateAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPOTPAuthenticatorActivatingCIP_' ) && ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$user_otp_activate_code = get_user_meta( $user_id, 'user_otp_activate_code', true );
		if( !empty( $_POST['code'] ) ){
			if( $_POST['code'] == $user_otp_activate_code ){
				update_user_meta( $user_id, 'otp_auth_key', 1 );
				// delete_user_meta( $user_id, 'google_auth_key' );
				delete_user_meta( $user_id, 'user_otp_activate_code' );
				$out = array( "error" => 0,'msg' => __('Email OTP authentication activated.','corsair-login') );

				$logs = sprintf( __('2FA OTP authentication activated by %s at %s', 'corsair-login'), $current_user->user_email, date_i18n('d/m/Y H:i A') );
				create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid OTP code.','corsair-login') );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter valid OTP code.','corsair-login') );
		}
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_otpAuth2FDeAactivateAct', 'corsair_login_otpAuth2FDeAactivateAct_callback' );
function corsair_login_otpAuth2FDeAactivateAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPOTPAuthenticatorDeActivatingCIP_' ) && ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$user_otp_deactivate_code = get_user_meta( $user_id, 'user_otp_deactivate_code', true );
		if( !empty( $_POST['code'] ) ){
			if( $_POST['code'] == $user_otp_deactivate_code ){
				delete_user_meta( $user_id, 'otp_auth_key', 1 );
				delete_user_meta( $user_id, 'user_otp_deactivate_code' );
				$out = array( "error" => 0,'msg' => __('Email OTP authentication deactivated.','corsair-login') );

				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

				$subject = sprintf(__("%s - Email OTP (disabled)", 'corsair-login'), $blogname);
				$message = sprintf( __('Dear member, <br/><p>Your email OTP (One-Time-Passcode) authentication has been disabled.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrl, $siteUrlName );

				add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
				add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
				add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

				$htmlContent = mailTemplateHtmlRender( $message );

				if( get_email_send_toggle('otp_enabled_disabled') == 1 ){
					$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
				}

				$logs = sprintf( __('2FA OTP authentication deactivated by %s at %s', 'corsair-login'), $current_user->user_email, date_i18n('d/m/Y H:i A') );
				create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid OTP code.','corsair-login') );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter valid OTP code.','corsair-login') );
		}
	}
	wp_send_json($out);
	exit;
}
function get_login_auth_type( $user_id = 0 ){
	$response = array('type' => '', 'status' => false, 'switch' => false );
	$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 );
	$otp_auth_key = get_user_meta( $user_id, 'otp_auth_key', 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 );
	$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_login == 1 ) ? 1 : 0;

	$status = false;
	if( ( $corsair_2fa_otp == 'yes' && $otp_auth_key == 1 ) && $corsair_2fa_ga == 'yes' && $ga2fa_login_enabled == 1 ){
		$response['type'] = 'both';
		$response['status'] = true;
		$response['switch'] = true;
	}else if( $corsair_2fa_otp == 'yes' && $otp_auth_key == 1 ){
		$response['type'] = 'otp';
		$response['status'] = true;
	}else if( $corsair_2fa_ga == 'yes' && $ga2fa_login_enabled == 1 ){
		$response['type'] = '2fa';
		$response['status'] = true;
	}
	return $response;
}
add_action( 'wp_ajax_cl_reset2faauth_act', 'cl_reset2faauth_act_callback' );
function cl_reset2faauth_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_XyReset2FaAuthyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$decrypted_id_raw = base64_decode( $_POST['thisid'] );
		$decryptedType = base64_decode( $_POST['thistype'] );
		$user_id = preg_replace(sprintf('/%s/', md5('324CL_MembeR_CL324') ), '', $decrypted_id_raw);
		$memberInfo = get_userdata($user_id);
		$reset = false;
		if( $user_id ){
			$memberInfo = get_userdata($user_id);
			if( $memberInfo ){

				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );
				$currentUserData = get_user_by( 'id', get_current_user_id() );

				$isSendEmail = false;

				if( $decryptedType == md5( 'EmailOtpReset' ) ){
					delete_user_meta( $user_id, 'otp_auth_key' );
					$subject = sprintf(__("%s - Email OTP (disabled)", 'corsair-login'), $blogname);
					$message = sprintf( __('Dear member, <br/><p>Your email OTP (One-Time-Passcode) authentication has been disabled.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrl, $siteUrlName );
					$logs = sprintf( __('Email OTP (One-Time-Passcode) Authentication Disabled of %s by %s at %s', 'corsair-login'),$memberInfo->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$reset = true;

					if( get_email_send_toggle('otp_enabled_disabled') == 1 ){
						$isSendEmail = true;
					}

				}else if( $decryptedType == md5( 'Google2FAReset' ) ){
					delete_user_meta( $user_id, 'google_auth_key' );
					delete_user_meta( $user_id, 'google_auth_key_login' );
					delete_user_meta( $user_id, 'google_auth_key_withdrawal' );
					$subject = sprintf(__("%s - Google 2FA (disabled)", 'corsair-login'), $blogname);
					$message = sprintf( __('Dear member, <br/><p>Your Google 2FA authentication has been disabled.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrl, $siteUrlName );
					$logs = sprintf( __('Google 2FA Authentication Disabled of %s by %s at %s', 'corsair-login'),$memberInfo->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$reset = true;
					if( get_email_send_toggle('2fa_enabled_disabled') == 1 ){
						$isSendEmail = true;
					}
				}
				if( $reset === true ){

					add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
					add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
					add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

					$htmlContent = mailTemplateHtmlRender( $message );

					if( $isSendEmail ){
						$sent_mail = wp_mail( $memberInfo->user_email, $subject, $htmlContent );
					}

					create_corsairlogin_logs_entry( 0, 'member', '','sm', $logs, true  );
					$out = array( "error" => 0,'msg' => __('Reset successfully.','corsair-login') );
				}

			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cl_resetpwd_act', 'cl_resetpwd_act_callback' );
function cl_resetpwd_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_XyResetPWDLinkyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$decrypted_id_raw = base64_decode( $_POST['thisid'] );
		$decryptedType = base64_decode( $_POST['thistype'] );
		$user_id = preg_replace(sprintf('/%s/', md5('324CL_MembeR_CL324') ), '', $decrypted_id_raw);
		$user_info = get_userdata($user_id);
		$currentUserData = get_user_by( 'id', get_current_user_id() );
		if( $user_id ){
			$user_info = get_userdata($user_id);
			if( $user_info ){

				$unique = get_password_reset_key( $user_info );

				$unique_url = network_site_url("wp-login.php?action=rp&key=$unique&login=" . rawurlencode($user_info->user_login), 'login');

				$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

				add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
				add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
				add_filter('wp_mail_content_type', function(){ return "text/html"; } );
				$subject = sprintf(__("%s - Reset Password Link", 'corsair-login'), $blogname);

				$unique_url_txt = disable_email_link( $unique_url );

				$message = sprintf( __('<br><p>This is an e-mail from %s.</p> <p> You are receiving this email because we received a password reset request for your account.</p><br/> <p><a href="%s" target="_blank" REPLACE_STYLE>Reset Password</a></p><br/>If the button above does not work, paste this link into your web browser: <br> %s <br> If you did not make this request, you can safely ignore this e-mail.<br/><p>This is an automated message, please do not reply.</p><br/><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login'),$blogname, esc_url($unique_url), $unique_url_txt, $siteUrl, $siteUrlName );

				$htmlContent = mailTemplateHtmlRender( $message );

				$sent_mail = wp_mail( $user_info->user_email, $subject, $htmlContent );
				if ( !$sent_mail ){
					$out = array( "error" => 1,'msg' => __('There was a problem sending you email. Please try again or contact an admin.','corsair-login') );
				}else{
					$logs = sprintf( __('Password reset link sent of %s by %s at %s', 'corsair-login'),$user_info->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					create_corsairlogin_logs_entry( 0, 'member', '','sm', $logs, true  );
					$out = array( "error" => 0,'msg' => __('Password reset link sent.','corsair-login') );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cl_togglelogin_act', 'cl_togglelogin_act_callback' );
function cl_togglelogin_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_XyToggleLoginEnableX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$decrypted_id_raw = base64_decode( $_POST['thisid'] );
		$togglelogin = $_POST['togglelogin'];
		$user_id = preg_replace(sprintf('/%s/', md5('324CL_MembeR_CL324') ), '', $decrypted_id_raw);
		$user_info = get_userdata($user_id);
		$currentUserData = get_user_by( 'id', get_current_user_id() );
		if( $user_id ){
			$user_info = get_userdata($user_id);
			if( $user_info ){
				$currentStatus = __('Suspended', 'corsair-login');
				if( $togglelogin == 1 ){
					update_user_meta( $user_id, 'csrnow_login_enable', 1 );
					$logs = sprintf( __('Login enabled of %s by %s at %s', 'corsair-login'),$user_info->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$currentStatus = __('Enabled', 'corsair-login');
				}else{
					update_user_meta( $user_id, 'csrnow_login_enable', 0 );
					$logs = sprintf( __('Login suspended of %s by %s at %s', 'corsair-login'),$user_info->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
				}
				create_corsairlogin_logs_entry( 0, 'member', '','sm', $logs, true  );
				$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'statusLabel' => $currentStatus );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cl_togglewithdrawal_act', 'cl_togglewithdrawal_act_callback' );
function cl_togglewithdrawal_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_XyToggleWithdrawalSuspendX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$decrypted_id_raw = base64_decode( $_POST['thisid'] );
		$togglewithdrawal = $_POST['togglewithdrawal'];
		$user_id = preg_replace(sprintf('/%s/', md5('324CL_MembeR_CL324') ), '', $decrypted_id_raw);
		$user_info = get_userdata($user_id);
		$currentUserData = get_user_by( 'id', get_current_user_id() );
		if( $user_id ){
			$user_info = get_userdata($user_id);
			if( $user_info ){
				$currentStatus = __('Suspended', 'corsair-login');
				if( $togglewithdrawal == 1 ){
					update_user_meta( $user_id, 'csrnow_withdrawal_suspend', 1 );
					$logs = sprintf( __('Withdrawal suspended of %s by %s at %s', 'corsair-login'),$user_info->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
				}else{
					delete_user_meta( $user_id, 'csrnow_withdrawal_suspend' );
					$logs = sprintf( __('Withdrawal enable of %s by %s at %s', 'corsair-login'),$user_info->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$currentStatus = __('Enabled', 'corsair-login');
				}
				create_corsairlogin_logs_entry( 0, 'member', '','sm', $logs, true  );
				$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'statusLabel' => $currentStatus );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function disable_email_link($unique_url) {
	$unique_url_txt = str_replace('@', '&#x40;', '<p><span>' . esc_url( $unique_url ) . '</span></p>');
	$unique_url_txt = str_replace(':', '<span>:</span>', $unique_url_txt);
	$unique_url_txt = str_replace('.', '<span>.</span>', $unique_url_txt);
	return $unique_url_txt;
}
function is_send_kyc_notification( $user_id = 0 ){
	$is_send = false;
	if( $user_id ){
		$kyc_complete_notify_date = get_user_meta( $user_id, 'kyc_complete_notify_date', true );
		if( empty( $kyc_complete_notify_date ) ){
			$nextWeekDate = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +1 week"));
			update_user_meta( $user_id, 'kyc_complete_notify_date', $nextWeekDate );
			$is_send = true;
		}else if( !empty( $kyc_complete_notify_date ) ){
			if( strtotime($kyc_complete_notify_date) < time() ){
				$nextWeekDate = date("Y-m-d H:i" ,strtotime(date('Y-m-d H:i')." +1 week"));
				update_user_meta( $user_id, 'kyc_complete_notify_date', $nextWeekDate );
				$is_send = true;
			}
		}
	}
	return $is_send;
}
add_action('wp_ajax_dont_show_profile_page_action', 'dont_show_profile_page_action_logged_in_cb');
function dont_show_profile_page_action_logged_in_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		update_user_meta( $user_id, 'dont_show_2fa_profile_popup', 1 );
		$out = array( "error" => 0,'msg' => __('Success','corsair-login') );
	}
	echo wp_json_encode( $out );
	exit;
}
// 5753 code
add_action('wp_ajax_check_for_user_ga_twofa', 'check_for_user_ga_twofa_cb');
function check_for_user_ga_twofa_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( ( current_user_can( 'member' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'login' || $_POST['thisType'] == 'withdrawal' ) ) ? $_POST['thisType'] : '-';
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		if( !empty( $google_auth_key ) ){
			$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'isopen' => 0 );
			if( $thisType == 'login' ){
				update_user_meta( $user_id, 'google_auth_key_login', 1 );
			}else if( $thisType == 'withdrawal' ){
				update_user_meta( $user_id, 'google_auth_key_withdrawal', 1 );
			}
			$logs = sprintf( __('2FA google authenticator activated for %s by %s at %s', 'corsair-login'), $thisType, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );
		}else{
			$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'isopen' => 1 );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_disable_for_user_ga_twofa', 'disable_for_user_ga_twofa_cb');
function disable_for_user_ga_twofa_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( current_user_can( 'member' ) && wp_verify_nonce( $_POST['_micro'],'_CL_Toogle2FAMicro_LC_' ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'login' || $_POST['thisType'] == 'withdrawal' ) ) ? $_POST['thisType'] : '-';
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );

		if( !empty( $_POST['code'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['code'], 0) ){

				/* $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
				$siteUrl = get_bloginfo('url');
				$siteUrlName = trim( str_replace( array( 'http://', 'https://' ), '', $siteUrl ), '/' );

				$subject = sprintf(__("%s - Google 2FA (disabled)", 'corsair-login'), $blogname);
				$message = sprintf( __('Dear member, <br/><p>Your Google 2FA authentication has been disabled.</p><br/><p>This is an automated message, please do not reply.</p><p>Best regards,<br/><a href="%s">%s</a> powered by Amplivo Limited</p>', 'corsair-login' ), $siteUrl, $siteUrlName );

				add_filter( 'wp_mail_from', function(){ return 'noreply@'.$_SERVER['HTTP_HOST']; } );
				add_filter( 'wp_mail_from_name', function(){ return sprintf( __( '%s','corsair-login'), get_option('blogname') ); } );
				add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );

				$htmlContent = mailTemplateHtmlRender( $message );
				$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent ); */

				$out = array( "error" => 0,'msg' => __('Google 2FA (Withdrawals and some other secure activities are disabled for 1 working day after Google 2FA is disabled)','corsair-login'), 'thisType' => $thisType );
				if( $thisType == 'login' ){
					delete_user_meta( $user_id, 'google_auth_key_login' );
				}else if( $thisType == 'withdrawal' ){
					delete_user_meta( $user_id, 'google_auth_key_withdrawal' );
				}
				$logs = sprintf( __('2FA google authenticator disabled for %s by %s at %s', 'corsair-login'), $thisType, $current_user->user_email, date_i18n('d/m/Y H:i A') );
				create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid 6-digit google authenticator code.','corsair-login') );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter 6-digit google authenticator code.','corsair-login') );
		}

		/* if( !empty( $google_auth_key ) ){
			$out = array( "error" => 0,'msg' => __('Google 2FA (Withdrawals and some other secure activities are disabled for 1 working day after Google 2FA is disabled)','corsair-login'), 'isopen' => 0 );
			if( $thisType == 'login' ){
				delete_user_meta( $user_id, 'google_auth_key_login' );
			}else if( $thisType == 'withdrawal' ){
				delete_user_meta( $user_id, 'google_auth_key_withdrawal' );
			}
			$logs = sprintf( __('2FA google authenticator disabled for %s by %s at %s', 'corsair-login'), $thisType, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_corsairlogin_logs_entry( $user_id, 'profile', '','member', $logs, true  );
		} */
	}
	wp_send_json($out);
	exit;
}