<?php
/**
 * Plugin Name: CIP Helper
 * Description: CIP Helper
 * Version: 0.48
 * Author: Corsair
 * Author URI: https://corsairnow.com/
 * Text Domain: cip-helper
 */
define( 'CIP_TXTDOMAIN', 'cip-helper' );
define( 'CIP_PLUGIN_FOLDER', plugin_dir_url(__FILE__) );
define( 'CIP_PLUGIN_BASE', plugin_dir_path(__FILE__) );
register_activation_hook( __FILE__, "activate_cip_helper" );
//register_deactivation_hook( __FILE__, "deactivate_cip_helper" );
//activation script
function activate_cip_helper(){
	global $table_prefix, $wpdb;
	$thTable = $table_prefix . 'token_holder';
	$logsTable = $table_prefix . 'cip_logs';
	$thTableCol = $table_prefix . 'token_holder_columns';
	$invoice= $table_prefix.'cip_member_invoice';
	$invoice_paid= $table_prefix.'cip_member_invoice_paid';
	$signValidateTable = $table_prefix.'eth_sign_validate';
	$account= $table_prefix.'sm_accounts_management';
	$charset_collate = $wpdb->get_charset_collate();
	//create token holder table if not exists
	if( $wpdb->get_var( "show tables like '$thTable'" ) != $thTable ) {
		$tokenHolderSql = "CREATE TABLE `$thTable` (
			`id` INT(11) NOT NULL auto_increment,
			`reference` VARCHAR(200) COLLATE utf8_general_ci,
			`eth_address` VARCHAR(250) COLLATE utf8_general_ci,
			`occurs_times` INT(11),
			`csr_amount_initial` INT(11),
			`csramount_by_ethaddress` DOUBLE,
			`csr_amount_issued` INT(11),
			`amount_due` INT(11),
			`username` VARCHAR(200) COLLATE utf8_general_ci,
			`csramount_byusername` INT(11),
			`occurs_times_user` INT(11),
			`first_name` VARCHAR(200) COLLATE utf8_general_ci,
			`last_name` VARCHAR(200) COLLATE utf8_general_ci,
			`redemption_date` VARCHAR(100) COLLATE utf8_general_ci,
			`claim_date` VARCHAR(100) COLLATE utf8_general_ci,
			`email` VARCHAR(100) COLLATE utf8_general_ci,
			`_user_status` VARCHAR(100) COLLATE utf8_general_ci,
			`kyc_status` VARCHAR(100) COLLATE utf8_general_ci,
			`pool_ref` VARCHAR(100),
			`approvedkyc` VARCHAR(250) COLLATE utf8_general_ci,
			`corp_approved` VARCHAR(250) COLLATE utf8_general_ci,
			`notes_external` LONGTEXT COLLATE utf8_general_ci,
			`notes_internal` LONGTEXT COLLATE utf8_general_ci,
			`position` INT(11),
			`text_1` VARCHAR(250) COLLATE utf8_general_ci,
			`text_2` VARCHAR(250) COLLATE utf8_general_ci,
			`text_3` VARCHAR(250) COLLATE utf8_general_ci,
			`text_4` VARCHAR(250) COLLATE utf8_general_ci,
			`text_5` VARCHAR(250) COLLATE utf8_general_ci,
			`text_6` VARCHAR(250) COLLATE utf8_general_ci,
			`text_7` VARCHAR(250) COLLATE utf8_general_ci,
			`text_8` VARCHAR(250) COLLATE utf8_general_ci,
			`text_9` VARCHAR(250) COLLATE utf8_general_ci,
			`text_10` VARCHAR(250) COLLATE utf8_general_ci,
			`date_1` VARCHAR(100) COLLATE utf8_general_ci,
			`date_2` VARCHAR(100) COLLATE utf8_general_ci,
			`date_3` VARCHAR(100) COLLATE utf8_general_ci,
			`date_4` VARCHAR(100) COLLATE utf8_general_ci,
			`date_5` VARCHAR(100) COLLATE utf8_general_ci,
			`date_6` VARCHAR(100) COLLATE utf8_general_ci,
			`date_7` VARCHAR(100) COLLATE utf8_general_ci,
			`date_8` VARCHAR(100) COLLATE utf8_general_ci,
			`date_9` VARCHAR(100) COLLATE utf8_general_ci,
			`date_10` VARCHAR(100) COLLATE utf8_general_ci,
			`int_1` INT(11),
			`int_2` INT(11),
			`int_3` INT(11),
			`int_4` INT(11),
			`int_5` INT(11),
			`int_6` INT(11),
			`int_7` INT(11),
			`int_8` INT(11),
			`int_9` INT(11),
			`int_10` INT(11),
			`note_1` LONGTEXT,
			`note_2` LONGTEXT,
			`note_3` LONGTEXT,
			`note_4` LONGTEXT,
			`note_5` LONGTEXT,
			`note_6` LONGTEXT,
			`note_7` LONGTEXT,
			`note_8` LONGTEXT,
			`note_9` LONGTEXT,
			`note_10` LONGTEXT,
			`imported_by` INT(11),
			`import_at` VARCHAR(100) COLLATE utf8_general_ci,
			`last_update_at` VARCHAR(100) COLLATE utf8_general_ci,
			`saved_amount`	BIGINT(20),
			`saving_date` VARCHAR(100) COLLATE utf8_general_ci,
			`saving_start_date` VARCHAR(100) COLLATE utf8_general_ci,
			`saving_interest` INT(11),
			`saving_periods` INT(11),
			`saving_state` INT(11),
			`sign_verify` INT(11),
			`transhash` LONGTEXT,
			`contract_address` VARCHAR(250) COLLATE utf8_general_ci,
			`receiver_address` VARCHAR(250) COLLATE utf8_general_ci,
			`ma_enabled` INT(11),
			PRIMARY KEY (`id`)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($tokenHolderSql);
	}
	//create logs table if not exists
	if( $wpdb->get_var( "show tables like '$logsTable'" ) != $logsTable ) {
		$cipLogsSql = "CREATE TABLE `$logsTable` (
			`id` INT(11) NOT NULL auto_increment,
			`user_id` INT(11),
			`user_type` VARCHAR(100),
			`log_type` VARCHAR(100),
			`logs` LONGTEXT,
			`_date` VARCHAR(100),
			PRIMARY KEY (`id`)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($cipLogsSql);
	}
	if( $wpdb->get_var( "show tables like '$thTableCol'" ) != $thTableCol ) {
		$tokenHolderColSql = "CREATE TABLE `$thTableCol` (
			`id` INT(11) NOT NULL auto_increment,
			`email` VARCHAR(200),
			`eth_address` VARCHAR(250),
			`columns` LONGTEXT,
			`_date` VARCHAR(200),
			PRIMARY KEY (`id`)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($tokenHolderColSql);
	}
	//create Member Invoice table if not exists
	if( $wpdb->get_var( "show tables like '$invoice'" ) != $invoice ) {
		$invoice_table = "CREATE TABLE `$invoice` (
			`id` INT(11) NOT NULL auto_increment,
			`BusinessName` VARCHAR(100) COLLATE utf8_general_ci,
			`BusinessCategory` VARCHAR(100) COLLATE utf8_general_ci,
			`Package` VARCHAR(100) COLLATE utf8_general_ci,
			`ProductPrice` VARCHAR(100) COLLATE utf8_general_ci,
			`Address1` VARCHAR(100) COLLATE utf8_general_ci,
			`Address2` VARCHAR(100) COLLATE utf8_general_ci,
			`City` VARCHAR(100) COLLATE utf8_general_ci,
			`State` VARCHAR(100) COLLATE utf8_general_ci,
			`Country` VARCHAR(100) COLLATE utf8_general_ci,
			`Zipcode` VARCHAR(100) COLLATE utf8_general_ci,
			`Employees` VARCHAR(100) COLLATE utf8_general_ci,
			`IntroducedBy` VARCHAR(100) COLLATE utf8_general_ci,
			`FirstName` VARCHAR(100) COLLATE utf8_general_ci,
			`LastName` VARCHAR(100) COLLATE utf8_general_ci,
			`Number` VARCHAR(100) COLLATE utf8_general_ci,
			`Email` VARCHAR(100) COLLATE utf8_general_ci,
			`CSRExchangeDiscount` VARCHAR(100) COLLATE utf8_general_ci,
			`PlasticWaste` VARCHAR(100) COLLATE utf8_general_ci,
			`PlasticWasteFootprint` VARCHAR(100) COLLATE utf8_general_ci,
			`Date` VARCHAR(100) COLLATE utf8_general_ci,
			`PaidDate` VARCHAR(100) COLLATE utf8_general_ci,
			`UniqueKey` VARCHAR(100) COLLATE utf8_general_ci,
			`Status` VARCHAR(100) COLLATE utf8_general_ci,
			`VatNumber` VARCHAR(100) COLLATE utf8_general_ci,
			`InvoiceNumber` BIGINT(20),
			`ProformaInvoiceNumber` BIGINT(20),
			`Kgs` VARCHAR(100) COLLATE utf8_general_ci,
			`Type` VARCHAR(100) COLLATE utf8_general_ci,
			`POVATAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`PONetAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`POGrossAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`POVATPercentage` VARCHAR(100) COLLATE utf8_general_ci,
			`VATAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`NetAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`GrossAmount` VARCHAR(100) COLLATE utf8_general_ci,
			`VATPercentage` VARCHAR(100) COLLATE utf8_general_ci,
			`Archive` VARCHAR(100) COLLATE utf8_general_ci,
			`Website` VARCHAR(100) COLLATE utf8_general_ci,
			`VATCountry` VARCHAR(100) COLLATE utf8_general_ci,
			`BankId` VARCHAR(100) COLLATE utf8_general_ci,
			`VATRate` INT(11),
			`ArchiveStatus` VARCHAR(100) COLLATE utf8_general_ci,
			PRIMARY KEY (`id`)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($invoice_table);
	}


	//create Member Invoice table if not exists
	if( $wpdb->get_var( "show tables like '$account'" ) != $account ) {
		$account_table = "CREATE TABLE `$account` (
		`id` INT(11) NOT NULL AUTO_INCREMENT ,
		`Status` VARCHAR(100) NULL ,
		`AccountHolder` VARCHAR(100) NULL ,
		`IBAN` VARCHAR(100) NULL ,
		`BIC` VARCHAR(100) NULL ,
		`BankCode` VARCHAR(50) NULL ,
		`BankName` VARCHAR(100) NULL ,
		`BankAddress` VARCHAR(150) NULL ,
		`AssignedTo` VARCHAR(100) NULL ,
		`Date` VARCHAR(50) NULL ,
		PRIMARY KEY  (`id`)
	) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($account_table);
	}
	if( $wpdb->get_var( "show tables like '$signValidateTable'" ) != $signValidateTable ) {
		$signValidateSql = "CREATE TABLE `$signValidateTable` (
			`id` INT(11) NOT NULL auto_increment,
			`email` VARCHAR(100) COLLATE utf8_general_ci,
			`eth_address` VARCHAR(250) NOT NULL,
			`verify_status` INT(11),
			`_date` VARCHAR(100),
			PRIMARY KEY (`id`)
		) $charset_collate;";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($signValidateSql);
	}
	$defaultColumnsArr = [
		// 'id'						=>	__('Id',CIP_TXTDOMAIN),
		'reference'					=>	__('Reference',CIP_TXTDOMAIN),
		'eth_address'				=>	__('ETH Address',CIP_TXTDOMAIN),
		'occurs_times'				=>	__('Occurs times',CIP_TXTDOMAIN),
		'csr_amount_initial'		=>	__('CSR Amount Initial',CIP_TXTDOMAIN),
		'csramount_by_ethaddress'	=>	__('CSR amount. By ETH address',CIP_TXTDOMAIN),
		'csr_amount_issued'			=>	__('CSR Amount Issued',CIP_TXTDOMAIN),
		'amount_due'				=>	__('Amount due',CIP_TXTDOMAIN),
		'username'					=>	__('Username',CIP_TXTDOMAIN),
		'csramount_byusername'		=>	__('CSR amount. By username',CIP_TXTDOMAIN),
		'occurs_times_user'			=>	__('Occurs times. By username',CIP_TXTDOMAIN),
		'first_name'				=>	__('First Name',CIP_TXTDOMAIN),
		'last_name'					=>	__('Last Name',CIP_TXTDOMAIN),
		'redemption_date'			=>	__('Redemption Date',CIP_TXTDOMAIN),
		'claim_date'				=>	__('Claim Date',CIP_TXTDOMAIN),
		'email'						=>	__('Email',CIP_TXTDOMAIN),
		'_user_status'				=>	__('User Status',CIP_TXTDOMAIN),
		'kyc_status'				=>	__('KYC Status',CIP_TXTDOMAIN),
		'pool_ref'					=>	__('Pool Ref',CIP_TXTDOMAIN),
		'approvedkyc'				=>	__('Approved KYC/Invalid Docs',CIP_TXTDOMAIN),
		'corp_approved'				=>	__('Corp Approved',CIP_TXTDOMAIN),
		'notes_external'			=>	__('Notes (External for member)',CIP_TXTDOMAIN),
		'notes_internal'			=>	__('Notes (Internal Private)',CIP_TXTDOMAIN),
		'position'					=>	__('Position',CIP_TXTDOMAIN),
		'text_1'					=>	__('text_1',CIP_TXTDOMAIN),
		'text_2'					=>	__('text_2',CIP_TXTDOMAIN),
		'text_3'					=>	__('text_3',CIP_TXTDOMAIN),
		'text_4'					=>	__('text_4',CIP_TXTDOMAIN),
		'text_5'					=>	__('text_5',CIP_TXTDOMAIN),
		'text_6'					=>	__('text_6',CIP_TXTDOMAIN),
		'text_7'					=>	__('text_7',CIP_TXTDOMAIN),
		'text_8'					=>	__('text_8',CIP_TXTDOMAIN),
		'text_9'					=>	__('text_9',CIP_TXTDOMAIN),
		'text_10'					=>	__('text_10',CIP_TXTDOMAIN),
		'date_1'					=>	__('date_1',CIP_TXTDOMAIN),
		'date_2'					=>	__('date_2',CIP_TXTDOMAIN),
		'date_3'					=>	__('date_3',CIP_TXTDOMAIN),
		'date_4'					=>	__('date_4',CIP_TXTDOMAIN),
		'date_5'					=>	__('date_5',CIP_TXTDOMAIN),
		'date_6'					=>	__('date_6',CIP_TXTDOMAIN),
		'date_7'					=>	__('date_7',CIP_TXTDOMAIN),
		'date_8'					=>	__('date_8',CIP_TXTDOMAIN),
		'date_9'					=>	__('date_9',CIP_TXTDOMAIN),
		'date_10'					=>	__('date_10',CIP_TXTDOMAIN),
		'int_1'						=>	__('int_1',CIP_TXTDOMAIN),
		'int_2'						=>	__('int_2',CIP_TXTDOMAIN),
		'int_3'						=>	__('int_3',CIP_TXTDOMAIN),
		'int_4'						=>	__('int_4',CIP_TXTDOMAIN),
		'int_5'						=>	__('int_5',CIP_TXTDOMAIN),
		'int_6'						=>	__('int_6',CIP_TXTDOMAIN),
		'int_7'						=>	__('int_7',CIP_TXTDOMAIN),
		'int_8'						=>	__('int_8',CIP_TXTDOMAIN),
		'int_9'						=>	__('int_9',CIP_TXTDOMAIN),
		'int_10'					=>	__('int_10',CIP_TXTDOMAIN),
		'note_1'					=>	__('note_1',CIP_TXTDOMAIN),
		'note_2'					=>	__('note_2',CIP_TXTDOMAIN),
		'note_3'					=>	__('note_3',CIP_TXTDOMAIN),
		'note_4'					=>	__('note_4',CIP_TXTDOMAIN),
		'note_5'					=>	__('note_5',CIP_TXTDOMAIN),
		'note_6'					=>	__('note_6',CIP_TXTDOMAIN),
		'note_7'					=>	__('note_7',CIP_TXTDOMAIN),
		'note_8'					=>	__('note_8',CIP_TXTDOMAIN),
		'note_9'					=>	__('note_9',CIP_TXTDOMAIN),
		'note_10'					=>	__('note_10',CIP_TXTDOMAIN),
		'imported_by'				=>	__('Imported By',CIP_TXTDOMAIN),
		'import_at'					=>	__('Import at',CIP_TXTDOMAIN),
		'last_update_at'			=>	__('Last Update',CIP_TXTDOMAIN),
		'saved_amount'				=>	__('saved amount',CIP_TXTDOMAIN),
		'saving_date'				=>	__('saving date',CIP_TXTDOMAIN),
		'saving_start_date'			=>	__('saving start date',CIP_TXTDOMAIN),
		'saving_interest'			=>	__('saving interest',CIP_TXTDOMAIN),
		'saving_periods'			=>	__('saving periods',CIP_TXTDOMAIN),
		'saving_state'				=>	__('saving state',CIP_TXTDOMAIN),
		'sign_verify'				=>	__('sign verify',CIP_TXTDOMAIN),
		'token'						=>	__('Token',CIP_TXTDOMAIN),
	];
	$column_order_arr = array();
	foreach( $defaultColumnsArr as $key => $defaultColumnArr ){
		$column_order_arr[] = $key;
	}
	update_option( 'cip_sm_column_order', $column_order_arr );
}
//deactivatation script
/*function deactivate_cip_helper(){
	global $table_prefix, $wpdb;
	$thTable = $table_prefix . 'token_holder';
	$logsTable = $table_prefix . 'cip_logs';
	$thTableCol = $table_prefix . 'token_holder_columns';
	$invoice= $table_prefix.'cip_member_invoice';
	$account= $table_prefix.'sm_accounts_management';
	//delete token holder table if not exists
	if( $wpdb->get_var( "show tables like '$thTable'" ) == $thTable ){
		$tokenHolderSql = "DROP TABLE IF EXISTS $thTable";
		require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
		$wpdb->query($tokenHolderSql);
	}
	//delete cip logs table if not exists
	if( $wpdb->get_var( "show tables like '$logsTable'" ) == $logsTable ){
		$cipLogsSql = "DROP TABLE IF EXISTS $logsTable";
		require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
		$wpdb->query($cipLogsSql);
	}
	if( $wpdb->get_var( "show tables like '$thTableCol'" ) == $thTableCol ){
		$tokenHolderColSql = "DROP TABLE IF EXISTS $thTableCol";
		require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
		$wpdb->query($tokenHolderColSql);
	}
	//delete invoice table if not exists
	if( $wpdb->get_var( "show tables like '$invoice'" ) == $invoice ){
		$invoiveSql = "DROP TABLE IF EXISTS $invoice";
		require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
		$wpdb->query($invoiveSql);
	}
	//delete SM Account Management table if not exists
	if( $wpdb->get_var( "show tables like '$account'" ) == $account ){
		$accountSql = "DROP TABLE IF EXISTS $account";
		require_once( ABSPATH . '/wp-admin/includes/upgrade.php' );
		$wpdb->query($accountSql);
	}
	// delete_option( 'cip_sm_column_labels' );
	// delete_option( 'cip_sm_column_order' );
	// delete_option( 'cip_column_sa_toggle_columns' );
	//delete_option( 'cip_column_th_toggle_columns' );
	// delete_option( 'cip_column_saedit_toggle_columns' );
	//delete_option( 'cip_routine_maintenance_mode' );
	$args = array( 'role__in'  =>	array('supportagent') );
	$users = get_users( $args );
	foreach( $users as $user ){
		delete_user_meta( $user->ID, 'cip_sagent_toggle_columns' );
	}
}*/
add_action( 'after_setup_theme', 'cip_global_var_for_default_column_arr_cb' );
function cip_global_var_for_default_column_arr_cb(){
	global $defaultColumnsArr;
	$defaultColumnsArr = [
		// 'id'						=>	__('Id',CIP_TXTDOMAIN),
		'reference'					=>	__('Reference',CIP_TXTDOMAIN),
		'eth_address'				=>	__('ETH Address',CIP_TXTDOMAIN),
		'occurs_times'				=>	__('Occurs times',CIP_TXTDOMAIN),
		'csr_amount_initial'		=>	__('CSR Amount Initial',CIP_TXTDOMAIN),
		'csramount_by_ethaddress'	=>	__('CSR amount. By ETH address',CIP_TXTDOMAIN),
		'csr_amount_issued'			=>	__('CSR Amount Issued',CIP_TXTDOMAIN),
		'amount_due'				=>	__('Amount due',CIP_TXTDOMAIN),
		'username'					=>	__('Username',CIP_TXTDOMAIN),
		'csramount_byusername'		=>	__('CSR amount. By username',CIP_TXTDOMAIN),
		'occurs_times_user'			=>	__('Occurs times. By username',CIP_TXTDOMAIN),
		'first_name'				=>	__('First Name',CIP_TXTDOMAIN),
		'last_name'					=>	__('Last Name',CIP_TXTDOMAIN),
		'redemption_date'			=>	__('Redemption Date',CIP_TXTDOMAIN),
		'claim_date'				=>	__('Claim Date',CIP_TXTDOMAIN),
		'email'						=>	__('Email',CIP_TXTDOMAIN),
		'_user_status'				=>	__('User Status',CIP_TXTDOMAIN),
		'kyc_status'				=>	__('KYC Status',CIP_TXTDOMAIN),
		'pool_ref'					=>	__('Pool Ref',CIP_TXTDOMAIN),
		'approvedkyc'				=>	__('Approved KYC/Invalid Docs',CIP_TXTDOMAIN),
		'corp_approved'				=>	__('Corp Approved',CIP_TXTDOMAIN),
		'notes_external'			=>	__('Notes (External for member)',CIP_TXTDOMAIN),
		'notes_internal'			=>	__('Notes (Internal Private)',CIP_TXTDOMAIN),
		'position'					=>	__('Position',CIP_TXTDOMAIN),
		'text_1'					=>	__('text_1',CIP_TXTDOMAIN),
		'text_2'					=>	__('text_2',CIP_TXTDOMAIN),
		'text_3'					=>	__('text_3',CIP_TXTDOMAIN),
		'text_4'					=>	__('text_4',CIP_TXTDOMAIN),
		'text_5'					=>	__('text_5',CIP_TXTDOMAIN),
		'text_6'					=>	__('text_6',CIP_TXTDOMAIN),
		'text_7'					=>	__('text_7',CIP_TXTDOMAIN),
		'text_8'					=>	__('text_8',CIP_TXTDOMAIN),
		'text_9'					=>	__('text_9',CIP_TXTDOMAIN),
		'text_10'					=>	__('text_10',CIP_TXTDOMAIN),
		'date_1'					=>	__('date_1',CIP_TXTDOMAIN),
		'date_2'					=>	__('date_2',CIP_TXTDOMAIN),
		'date_3'					=>	__('date_3',CIP_TXTDOMAIN),
		'date_4'					=>	__('date_4',CIP_TXTDOMAIN),
		'date_5'					=>	__('date_5',CIP_TXTDOMAIN),
		'date_6'					=>	__('date_6',CIP_TXTDOMAIN),
		'date_7'					=>	__('date_7',CIP_TXTDOMAIN),
		'date_8'					=>	__('date_8',CIP_TXTDOMAIN),
		'date_9'					=>	__('date_9',CIP_TXTDOMAIN),
		'date_10'					=>	__('date_10',CIP_TXTDOMAIN),
		'int_1'						=>	__('int_1',CIP_TXTDOMAIN),
		'int_2'						=>	__('int_2',CIP_TXTDOMAIN),
		'int_3'						=>	__('int_3',CIP_TXTDOMAIN),
		'int_4'						=>	__('int_4',CIP_TXTDOMAIN),
		'int_5'						=>	__('int_5',CIP_TXTDOMAIN),
		'int_6'						=>	__('int_6',CIP_TXTDOMAIN),
		'int_7'						=>	__('int_7',CIP_TXTDOMAIN),
		'int_8'						=>	__('int_8',CIP_TXTDOMAIN),
		'int_9'						=>	__('int_9',CIP_TXTDOMAIN),
		'int_10'					=>	__('int_10',CIP_TXTDOMAIN),
		'note_1'					=>	__('note_1',CIP_TXTDOMAIN),
		'note_2'					=>	__('note_2',CIP_TXTDOMAIN),
		'note_3'					=>	__('note_3',CIP_TXTDOMAIN),
		'note_4'					=>	__('note_4',CIP_TXTDOMAIN),
		'note_5'					=>	__('note_5',CIP_TXTDOMAIN),
		'note_6'					=>	__('note_6',CIP_TXTDOMAIN),
		'note_7'					=>	__('note_7',CIP_TXTDOMAIN),
		'note_8'					=>	__('note_8',CIP_TXTDOMAIN),
		'note_9'					=>	__('note_9',CIP_TXTDOMAIN),
		'note_10'					=>	__('note_10',CIP_TXTDOMAIN),
		'imported_by'				=>	__('Imported By',CIP_TXTDOMAIN),
		'import_at'					=>	__('Import at',CIP_TXTDOMAIN),
		'last_update_at'			=>	__('Last Update',CIP_TXTDOMAIN),
		'saved_amount'				=>	__('saved amount',CIP_TXTDOMAIN),
		'saving_date'				=>	__('saving date',CIP_TXTDOMAIN),
		'saving_start_date'			=>	__('saving start date',CIP_TXTDOMAIN),
		'saving_interest'			=>	__('saving interest',CIP_TXTDOMAIN),
		'saving_periods'			=>	__('saving periods',CIP_TXTDOMAIN),
		'saving_state'				=>	__('saving state',CIP_TXTDOMAIN),
		'sign_verify'				=>	__('sign verify',CIP_TXTDOMAIN),
		'token'						=>	__('Token',CIP_TXTDOMAIN),
	];
	if (!current_user_can('administrator') && !is_admin()) {
  		show_admin_bar(false);
	}
}
//admin menu for listing token holder
add_action('admin_menu', 'cip_menu_tokenholder_records_cb');
function cip_menu_tokenholder_records_cb(){
	add_submenu_page( 'users.php', __('Token Holders',CIP_TXTDOMAIN), __('Token Holders',CIP_TXTDOMAIN), 'manage_options', 'token-holders', 'cip_show_tokenholder_records_cb', null );
	add_submenu_page( 'users.php', __( 'CIP Helper', CIP_TXTDOMAIN ), __( 'CIP Helper', CIP_TXTDOMAIN ), 'manage_options', 'cip-helper', 'ciphelper_setting_option_content' );
}
function cip_show_tokenholder_records_cb(){
	include 'admin/cip_tknhldr_page.php';
}
add_action('admin_init', 'ciphelper_options_settings');
function ciphelper_options_settings(){
	register_setting( 'cip_options_group', 'cipoptions' );
}
function ciphelper_setting_option_content(){
	$cipoptions = (array)get_option('cipoptions');
	?>
	<div>
  		<h2><?php _e('CIP Helper',CIP_TXTDOMAIN); ?></h2>
	  	<form method="post" action="options.php">
	  	<?php settings_fields( 'cip_options_group' ); ?>
	  	<table>
	  		<tr valign="top">
	  			<th scope="row"><label for="routine_maintenance_page"><?php _e('Routine maintenance',CIP_TXTDOMAIN); ?></label></th>
	  			<td><input type="text" class="regular-text" id="routine_maintenance_page" name="cipoptions[routine_maintenance_page]" value="<?php echo $cipoptions['routine_maintenance_page']; ?>" /></td>
	  	</tr>
	  	</table>
	  <?php submit_button(); ?>
	  </form>
  	</div>
	<?php
}
add_action( 'template_redirect', 'my_page_template_redirect' );
function my_page_template_redirect(){
	$cipoptions = (array)get_option('cipoptions');
	$routine_maintenance = get_option('cip_routine_maintenance_mode'); //live
	$member_maintenance = get_option('cip_member_maintenance_mode');
	$site_maintenance = get_option('cip_site_maintenance_mode'); //whole
	$login_page_id = get_option( 'login_page_url' );
	$userData = wp_get_current_user();
	$user_roles = $userData->roles;
	if( $cipoptions['routine_maintenance_page'] == get_the_ID() && ( $routine_maintenance != 1 && $site_maintenance != 1 && $member_maintenance != 1 ) ){
		wp_redirect( get_permalink( $login_page_id ) );
		exit();
	}

    /* if( $routine_maintenance == 1 && !is_page(  $login_page_id ) && $cipoptions['routine_maintenance_page'] != get_the_ID() ){
		if( !in_array("administrator",$userData->roles) && !in_array("supportmanager",$userData->roles) && !in_array("supportagent",$userData->roles) ){
			if( is_user_logged_in() ){
				$current_user = wp_get_current_user();
				$sessions = WP_Session_Tokens::get_instance( $current_user->ID );
				$sessions->destroy_all();
			}
			wp_redirect( get_permalink( $cipoptions['routine_maintenance_page'] ) );
			exit();
		}
    } */
    if( $site_maintenance == 1 && !is_page(  $login_page_id ) && $cipoptions['routine_maintenance_page'] != get_the_ID() && !is_page('header-notice-iframe')){
		if( !in_array("administrator",$userData->roles) && !in_array("supportmanager",$userData->roles) && !in_array("supportagent",$userData->roles) ){
			if( is_user_logged_in() ){
				$current_user = wp_get_current_user();
				$sessions = WP_Session_Tokens::get_instance( $current_user->ID );
				$sessions->destroy_all();
			}
			wp_redirect( get_permalink( $cipoptions['routine_maintenance_page'] ) );
			exit();
		}
    }

	/* $user_role = array_shift($user_roles);
    if(!($user_role == "supportmanager" || $user_role == 'administrator' || $user_role == 'supportagent')){
		if( $site_maintenance == 1 && $cipoptions['routine_maintenance_page'] != get_the_ID() ){

			if( is_user_logged_in() ){
				$current_user = wp_get_current_user();
				$sessions = WP_Session_Tokens::get_instance( $current_user->ID );
				$sessions->destroy_all();
			}
			wp_redirect( get_permalink( $cipoptions['routine_maintenance_page'] ) );
			exit();
		}
	} */
}
add_action('wp_ajax_cip_import_csv_act','cip_import_csv_act_callback');
function cip_import_csv_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxthimportxCIP_' ) ){
		if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['is_fieldmap'] ) && $_POST['is_fieldmap'] == 'yes' ) ){ // field mapping
			$column_html = "";
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$file = $_FILES['th_csv_file']['tmp_name'];
				include( 'PHPExcel/Classes/PHPExcel/IOFactory.php' );
				$inputFileName = $file;
				try {
					$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objReader->setInputEncoding('ISO-8859-1');
					$objPHPExcel = $objReader->load($inputFileName);
				}catch(Exception $e){
					$out = array( "error" => 1,'msg' => $e->getMessage() );
					echo wp_json_encode( $out );
					exit;
				}
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow();
				$highestColumn = $sheet->getHighestColumn();
				$row = 1;
				$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

				$columnsArr = [
					'reference'					=> __('Reference',CIP_TXTDOMAIN),
					'eth_address'				=> __('ETH Address',CIP_TXTDOMAIN),
					'occurs_times'				=> __('Occurs times',CIP_TXTDOMAIN),
					'csr_amount_initial'		=> __('CSR Amount Initial',CIP_TXTDOMAIN),
					'csramount_by_ethaddress'	=> __('CSR amount. By ETH address',CIP_TXTDOMAIN),
					'csr_amount_issued'			=> __('CSR Amount Issued',CIP_TXTDOMAIN),
					'amount_due'				=> __('Amount due',CIP_TXTDOMAIN),
					'username'					=> __('Username',CIP_TXTDOMAIN),
					'csramount_byusername'		=> __('CSR amount. By username',CIP_TXTDOMAIN),
					'occurs_times_user'			=> __('Occurs times. By username',CIP_TXTDOMAIN),
					'first_name'				=> __('First Name',CIP_TXTDOMAIN),
					'last_name'					=> __('Last Name',CIP_TXTDOMAIN),
					'redemption_date'			=> __('Redemption Date',CIP_TXTDOMAIN),
					'claim_date'				=> __('Claim Date',CIP_TXTDOMAIN),
					'email'						=> __('Email',CIP_TXTDOMAIN),
					'_user_status'				=> __('User Status',CIP_TXTDOMAIN),
					'kyc_status'				=> __('KYC Status',CIP_TXTDOMAIN),
					'pool_ref'					=> __('Pool Ref',CIP_TXTDOMAIN),
					'approvedkyc'				=> __('Approved KYC/Invalid Docs',CIP_TXTDOMAIN),
					'corp_approved'				=> __('Corp Approved',CIP_TXTDOMAIN),
					'notes_external'			=> __('Notes (External for member)',CIP_TXTDOMAIN),
					'notes_internal'			=> __('Notes (Internal Private)',CIP_TXTDOMAIN),
					'position'					=> __('Position',CIP_TXTDOMAIN),
					'text_1'					=>	__('text_1',CIP_TXTDOMAIN),
					'text_2'					=>	__('text_2',CIP_TXTDOMAIN),
					'text_3'					=>	__('text_3',CIP_TXTDOMAIN),
					'text_4'					=>	__('text_4',CIP_TXTDOMAIN),
					'text_5'					=>	__('text_5',CIP_TXTDOMAIN),
					'text_6'					=>	__('text_6',CIP_TXTDOMAIN),
					'text_7'					=>	__('text_7',CIP_TXTDOMAIN),
					'text_8'					=>	__('text_8',CIP_TXTDOMAIN),
					'text_9'					=>	__('text_9',CIP_TXTDOMAIN),
					'text_10'					=>	__('text_10',CIP_TXTDOMAIN),
					'date_1'					=>	__('date_1',CIP_TXTDOMAIN),
					'date_2'					=>	__('date_2',CIP_TXTDOMAIN),
					'date_3'					=>	__('date_3',CIP_TXTDOMAIN),
					'date_4'					=>	__('date_4',CIP_TXTDOMAIN),
					'date_5'					=>	__('date_5',CIP_TXTDOMAIN),
					'date_6'					=>	__('date_6',CIP_TXTDOMAIN),
					'date_7'					=>	__('date_7',CIP_TXTDOMAIN),
					'date_8'					=>	__('date_8',CIP_TXTDOMAIN),
					'date_9'					=>	__('date_9',CIP_TXTDOMAIN),
					'date_10'					=>	__('date_10',CIP_TXTDOMAIN),
					'int_1'						=>	__('int_1',CIP_TXTDOMAIN),
					'int_2'						=>	__('int_2',CIP_TXTDOMAIN),
					'int_3'						=>	__('int_3',CIP_TXTDOMAIN),
					'int_4'						=>	__('int_4',CIP_TXTDOMAIN),
					'int_5'						=>	__('int_5',CIP_TXTDOMAIN),
					'int_6'						=>	__('int_6',CIP_TXTDOMAIN),
					'int_7'						=>	__('int_7',CIP_TXTDOMAIN),
					'int_8'						=>	__('int_8',CIP_TXTDOMAIN),
					'int_9'						=>	__('int_9',CIP_TXTDOMAIN),
					'int_10'					=>	__('int_10',CIP_TXTDOMAIN),
					'note_1'					=>	__('note_1',CIP_TXTDOMAIN),
					'note_2'					=>	__('note_2',CIP_TXTDOMAIN),
					'note_3'					=>	__('note_3',CIP_TXTDOMAIN),
					'note_4'					=>	__('note_4',CIP_TXTDOMAIN),
					'note_5'					=>	__('note_5',CIP_TXTDOMAIN),
					'note_6'					=>	__('note_6',CIP_TXTDOMAIN),
					'note_7'					=>	__('note_7',CIP_TXTDOMAIN),
					'note_8'					=>	__('note_8',CIP_TXTDOMAIN),
					'note_9'					=>	__('note_9',CIP_TXTDOMAIN),
					'note_10'					=>	__('note_10',CIP_TXTDOMAIN),
					'saved_amount'				=>	__('Saved Amount',CIP_TXTDOMAIN),
					'saving_date'				=>	__('Saved Date',CIP_TXTDOMAIN),
					'saving_start_date'			=>	__('Saved Start Date',CIP_TXTDOMAIN),
					'saving_interest'			=>	__('Saved Interest',CIP_TXTDOMAIN),
					'saving_periods'			=>	__('Saved Periods',CIP_TXTDOMAIN),
					'sign_verify'				=>	__('Saved Verify',CIP_TXTDOMAIN),
					'transhash'					=>	__('Trans Hash',CIP_TXTDOMAIN),
					'contract_address'			=>	__('Contract Address',CIP_TXTDOMAIN),
					'receiver_address'			=>	__('Receiver Address',CIP_TXTDOMAIN),
					'ma_enabled'				=>	__('MA Enabled',CIP_TXTDOMAIN),
				];
				$column_html .= '<div class="row">';
				$selectKey = 0;
				foreach( $columnsArr as $key => $columnField ){
					// $first_word = explode(' ',trim($columnField));
					$first_word = $columnField;
					$required = '';
					if( $selectKey == 0 ){
						$required = 'required';
					}
					$column_html .= '<div class="col-4"><label>' . $columnField . '</label>';
					$column_html .= '<select name="fieldmap_col_' . $selectKey . '" ' . $required . ' >';
					$column_html .= '<option value="">------</option>';
					if( !empty( $rowData[0] ) ){
						foreach( $rowData[0] as $colKey => $column ){
							if(strpos( strtolower($column) , strtolower($key) ) !== false){
								$column_html .= '<option value="'.$colKey.'" selected>' . $column . '</option>';
							}else{
								$column_html .= '<option value="'.$colKey.'">' . $column . '</option>';
							}
						}
					}
					$column_html .= '</select>';
					$column_html .= '</div>';
					$selectKey++;
				}
				$column_html .= '</div>';
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $column_html );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}else{ // importing data
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$file = $_FILES['th_csv_file']['tmp_name'];
				include( 'PHPExcel/Classes/PHPExcel/IOFactory.php' );
				$inputFileName = $file;
				try {
					$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objReader->setInputEncoding('ISO-8859-1');
					$objPHPExcel = $objReader->load($inputFileName);
				}catch(Exception $e){
					$out = array( "error" => 1,'msg' => $e->getMessage() );
					echo wp_json_encode( $out );
					exit;
				}
				global $table_prefix, $wpdb;
				$thTable = $table_prefix . 'token_holder';
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow();
				$highestColumn = $sheet->getHighestColumn();
				$count = 2;
				$trDanger = "table-danger";
				$trSuccess = "table-success";
				$logs = "";
				cip_clear_logs();
				for($row = 2; $row <= $highestRow; $row++){
					$rowError = false;
					$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);

					$reference = ( $rowData[0][ $_POST['fieldmap_col_0'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_0'] ] : '0';
					$eth_address = ( $rowData[0][ $_POST['fieldmap_col_1'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_1'] ] : '';
					$occurs_times = ( $rowData[0][ $_POST['fieldmap_col_2'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_2'] ] : '';
					$csr_amount_initial = ( $rowData[0][ $_POST['fieldmap_col_3'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_3'] ] : '';
					$csramount_by_ethaddress = ( $rowData[0][ $_POST['fieldmap_col_4'] ] != "" ) ? str_replace( ',', '', $rowData[0][ $_POST['fieldmap_col_4'] ]) : '';
					$csr_amount_issued = ( $rowData[0][ $_POST['fieldmap_col_5'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_5'] ] : '';
					$amount_due = ( $rowData[0][ $_POST['fieldmap_col_6'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_6'] ] : '';
					$username = ( $rowData[0][ $_POST['fieldmap_col_7'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_7'] ] : '';
					$username = iconv('UTF-8', 'windows-1252', $username);
					$csramount_byusername = ( $rowData[0][ $_POST['fieldmap_col_8'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_8'] ] : '';
					$occurs_times_user = ( $rowData[0][ $_POST['fieldmap_col_9'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_9'] ] : '';
					$first_name = ( $rowData[0][ $_POST['fieldmap_col_10'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_10'] ] : '';
					$first_name = iconv('UTF-8', 'windows-1252', $first_name);
					$last_name = ( $rowData[0][ $_POST['fieldmap_col_11'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_11'] ] : '';
					$last_name = iconv('UTF-8', 'windows-1252', $last_name);
					$redemption_date = ( $rowData[0][ $_POST['fieldmap_col_12'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_12'] ] : '';
					$claim_date = ( $rowData[0][ $_POST['fieldmap_col_13'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_13'] ] : '';
					$email = ( $rowData[0][ $_POST['fieldmap_col_14'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_14'] ] : '';
					$user_status = ( $rowData[0][ $_POST['fieldmap_col_15'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_15'] ] : '';
					$kyc_status = ( $rowData[0][ $_POST['fieldmap_col_16'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_16'] ] : '';
					$pool_ref = ( $rowData[0][ $_POST['fieldmap_col_17'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_17'] ] : '';
					$approvedkyc = ( $rowData[0][ $_POST['fieldmap_col_18'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_18'] ] : '';
					$corp_approved = ( $rowData[0][ $_POST['fieldmap_col_19'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_19'] ] : '';
					$notes_external = ( $rowData[0][ $_POST['fieldmap_col_20'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_20'] ] : '';
					$notes_internal = ( $rowData[0][ $_POST['fieldmap_col_21'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_21'] ] : '';
					$position = ( $rowData[0][ $_POST['fieldmap_col_22'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_22'] ] : null;

					$text_1 = ( $rowData[0][ $_POST['fieldmap_col_23'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_23'] ] : null;
					$text_2 = ( $rowData[0][ $_POST['fieldmap_col_24'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_24'] ] : null;
					$text_3 = ( $rowData[0][ $_POST['fieldmap_col_25'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_25'] ] : null;
					$text_4 = ( $rowData[0][ $_POST['fieldmap_col_26'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_26'] ] : null;
					$text_5 = ( $rowData[0][ $_POST['fieldmap_col_27'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_27'] ] : null;
					$text_6 = ( $rowData[0][ $_POST['fieldmap_col_28'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_28'] ] : null;
					$text_7 = ( $rowData[0][ $_POST['fieldmap_col_29'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_29'] ] : null;
					$text_8 = ( $rowData[0][ $_POST['fieldmap_col_30'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_30'] ] : null;
					$text_9 = ( $rowData[0][ $_POST['fieldmap_col_31'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_31'] ] : null;
					$text_10 = ( $rowData[0][ $_POST['fieldmap_col_32'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_32'] ] : null;

					$date_1 = ( $rowData[0][ $_POST['fieldmap_col_33'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_33'] ] : null;
					$date_2 = ( $rowData[0][ $_POST['fieldmap_col_34'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_34'] ] : null;
					$date_3 = ( $rowData[0][ $_POST['fieldmap_col_35'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_35'] ] : null;
					$date_4 = ( $rowData[0][ $_POST['fieldmap_col_36'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_36'] ] : null;
					$date_5 = ( $rowData[0][ $_POST['fieldmap_col_37'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_37'] ] : null;
					$date_6 = ( $rowData[0][ $_POST['fieldmap_col_38'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_38'] ] : null;
					$date_7 = ( $rowData[0][ $_POST['fieldmap_col_39'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_39'] ] : null;
					$date_8 = ( $rowData[0][ $_POST['fieldmap_col_40'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_40'] ] : null;
					$date_9 = ( $rowData[0][ $_POST['fieldmap_col_41'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_41'] ] : null;
					$date_10 = ( $rowData[0][ $_POST['fieldmap_col_42'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_42'] ] : null;

					$int_1 = ( $rowData[0][ $_POST['fieldmap_col_43'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_43'] ] : null;
					$int_2 = ( $rowData[0][ $_POST['fieldmap_col_44'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_44'] ] : null;
					$int_3 = ( $rowData[0][ $_POST['fieldmap_col_45'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_45'] ] : null;
					$int_4 = ( $rowData[0][ $_POST['fieldmap_col_46'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_46'] ] : null;
					$int_5 = ( $rowData[0][ $_POST['fieldmap_col_47'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_47'] ] : null;
					$int_6 = ( $rowData[0][ $_POST['fieldmap_col_48'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_48'] ] : null;
					$int_7 = ( $rowData[0][ $_POST['fieldmap_col_49'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_49'] ] : null;
					$int_8 = ( $rowData[0][ $_POST['fieldmap_col_50'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_50'] ] : null;
					$int_9 = ( $rowData[0][ $_POST['fieldmap_col_51'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_51'] ] : null;
					$int_10 = ( $rowData[0][ $_POST['fieldmap_col_52'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_52'] ] : null;

					$note_1 = ( $rowData[0][ $_POST['fieldmap_col_53'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_53'] ] : null;
					$note_2 = ( $rowData[0][ $_POST['fieldmap_col_54'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_54'] ] : null;
					$note_3 = ( $rowData[0][ $_POST['fieldmap_col_55'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_55'] ] : null;
					$note_4 = ( $rowData[0][ $_POST['fieldmap_col_56'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_56'] ] : null;
					$note_5 = ( $rowData[0][ $_POST['fieldmap_col_57'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_57'] ] : null;
					$note_6 = ( $rowData[0][ $_POST['fieldmap_col_58'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_58'] ] : null;
					$note_7 = ( $rowData[0][ $_POST['fieldmap_col_59'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_59'] ] : null;
					$note_8 = ( $rowData[0][ $_POST['fieldmap_col_60'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_60'] ] : null;
					$note_9 = ( $rowData[0][ $_POST['fieldmap_col_61'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_61'] ] : null;
					$note_10 = ( $rowData[0][ $_POST['fieldmap_col_62'] ] != "" ) ? $rowData[0][ $_POST['fieldmap_col_62'] ] : null;
					$rowRawString = '<tr class="%s"><th scope="row">%s</th><td>%s</td><td>%s</td></tr>';
					if( isset( $_POST['update_existing'] ) && $_POST['update_existing'] == 1 ){ //update
						if( !empty( $reference ) ){
							$getSingleTh = $wpdb->get_row("SELECT id,reference FROM $thTable WHERE reference = '".$reference."'");
							if( !empty( $getSingleTh ) ){
								$validationError = [];
								if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
									$rowError = true;
									$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
								}
								if( !empty( $occurs_times ) && !is_numeric( $occurs_times ) ){
									$rowError = true;
									$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $csramount_by_ethaddress ) && !is_numeric( $csramount_by_ethaddress ) ){
									$rowError = true;
									$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
									$rowError = true;
									$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $amount_due ) && !is_numeric( $amount_due ) ){
									$rowError = true;
									$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $csramount_byusername ) && !is_numeric( $csramount_byusername ) ){
									$rowError = true;
									$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $csr_amount_issued ) && !is_numeric( $csr_amount_issued ) ){
									$rowError = true;
									$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $occurs_times_user ) && !is_numeric( $occurs_times_user ) ){
									$rowError = true;
									$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
								}
								if( !empty( $redemption_date ) && DateTime::createFromFormat('d/m/Y', $redemption_date) === false ){
									$rowError = true;
									$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
								}
								if( !empty( $claim_date ) && DateTime::createFromFormat('d/m/Y', $claim_date) === false ){
									$rowError = true;
									$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
								}
								if( !empty( $position ) && !is_numeric( $position ) ){
									$rowError = true;
									$validationError[] = __('Position is not numeric',CIP_TXTDOMAIN);
								}
								if( $rowError === true ){
									$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, implode(', ', $validationError) );
									$log_msg = $row . ' :: ' . $reference . ' :: ' . implode(', ', $validationError);
									cip_create_logs( $log_msg );
									continue;
								}
								$redemption_date_formatted = "";
								$claim_date_formatted = "";
								$formattedRDate = DateTime::createFromFormat('d/m/Y', $redemption_date);
								$formattedCDate = DateTime::createFromFormat('d/m/Y', $claim_date);
								if( $formattedRDate ){
									$redemption_date_formatted = $formattedRDate->format('d/m/Y');
								}
								if( $formattedCDate ){
									$claim_date_formatted = $formattedCDate->format('d/m/Y');
								}
								$where = [ 'id' => $getSingleTh->id ];
								$data = array();
								if( $reference ){
									$data['reference'] = wp_strip_all_tags( $reference );
								}
								if( $eth_address ){
									$data['eth_address'] = wp_strip_all_tags( $eth_address );
								}
								if( $occurs_times ){
									$data['occurs_times'] = wp_strip_all_tags( $occurs_times );
								}
								if( $csr_amount_initial ){
									$data['csr_amount_initial'] = wp_strip_all_tags( $csr_amount_initial );
								}
								if( $csramount_by_ethaddress ){
									$data['csramount_by_ethaddress'] = wp_strip_all_tags( $csramount_by_ethaddress );
								}
								if( $csr_amount_issued ){
									$data['csr_amount_issued'] = wp_strip_all_tags( $csr_amount_issued );
								}
								if( $amount_due ){
									$data['amount_due'] = wp_strip_all_tags( $amount_due );
								}
								if( $username ){
									$data['username'] = wp_strip_all_tags( wp_unslash( $username ) );
								}
								if( $csramount_byusername ){
									$data['csramount_byusername'] = wp_strip_all_tags( $csramount_byusername );
								}
								if( $occurs_times_user ){
									$data['occurs_times_user'] = wp_strip_all_tags( $occurs_times_user );
								}
								if( $first_name ){
									$data['first_name'] = wp_strip_all_tags( wp_unslash( $first_name ) );
								}
								if( $last_name ){
									$data['last_name'] = wp_strip_all_tags( wp_unslash( $last_name ) );
								}
								if( $redemption_date ){
									$data['redemption_date'] = wp_strip_all_tags( $redemption_date );
								}
								if( $claim_date ){
									$data['claim_date'] = wp_strip_all_tags( $claim_date );
								}
								if( $email ){
									$data['email'] = wp_strip_all_tags( $email );
								}
								if( $_user_status ){
									$data['_user_status'] = wp_strip_all_tags( $_user_status );
								}
								if( $kyc_status ){
									$data['kyc_status'] = wp_strip_all_tags( $kyc_status );
								}
								if( $pool_ref ){
									$data['pool_ref'] = wp_strip_all_tags( $pool_ref );
								}
								if( $approvedkyc ){
									$data['approvedkyc'] = wp_strip_all_tags( $approvedkyc );
								}
								if( $corp_approved ){
									$data['corp_approved'] = wp_strip_all_tags( $corp_approved );
								}
								if( $notes_external ){
									$data['notes_external'] = wp_strip_all_tags( wp_unslash( $notes_external ) );
								}
								if( $notes_internal ){
									$data['notes_internal'] = wp_strip_all_tags( wp_unslash( $notes_internal ) );
								}
								if( $position ){
									$data['position'] = wp_strip_all_tags( $position );
								}
								if( $text_1 ){
									$data['text_1'] = wp_strip_all_tags( $text_1 );
								}
								if( $text_2 ){
									$data['text_2'] = wp_strip_all_tags( $text_2 );
								}
								if( $text_3 ){
									$data['text_3'] = wp_strip_all_tags( $text_3 );
								}
								if( $text_4 ){
									$data['text_4'] = wp_strip_all_tags( $text_4 );
								}
								if( $text_5 ){
									$data['text_5'] = wp_strip_all_tags( $text_5 );
								}
								if( $text_6 ){
									$data['text_6'] = wp_strip_all_tags( $text_6 );
								}
								if( $text_7 ){
									$data['text_7'] = wp_strip_all_tags( $text_7 );
								}
								if( $text_8 ){
									$data['text_8'] = wp_strip_all_tags( $text_8 );
								}
								if( $text_9 ){
									$data['text_9'] = wp_strip_all_tags( $text_9 );
								}
								if( $text_10 ){
									$data['text_10'] = wp_strip_all_tags( $text_10 );
								}

								if( $date_1 ){
									$data['date_1'] = wp_strip_all_tags( $date_1 );
								}
								if( $date_2 ){
									$data['date_2'] = wp_strip_all_tags( $date_2 );
								}
								if( $date_3 ){
									$data['date_3'] = wp_strip_all_tags( $date_3 );
								}
								if( $date_4 ){
									$data['date_4'] = wp_strip_all_tags( $date_4 );
								}
								if( $date_5 ){
									$data['date_5'] = wp_strip_all_tags( $date_5 );
								}
								if( $date_6 ){
									$data['date_6'] = wp_strip_all_tags( $date_6 );
								}
								if( $date_7 ){
									$data['date_7'] = wp_strip_all_tags( $date_7 );
								}
								if( $date_8 ){
									$data['date_8'] = wp_strip_all_tags( $date_8 );
								}
								if( $date_9 ){
									$data['date_9'] = wp_strip_all_tags( $date_9 );
								}
								if( $date_10 ){
									$data['date_10'] = wp_strip_all_tags( $date_10 );
								}

								if( $int_1 ){
									$data['int_1'] = wp_strip_all_tags( $int_1 );
								}
								if( $int_2 ){
									$data['int_2'] = wp_strip_all_tags( $int_2 );
								}
								if( $int_3 ){
									$data['int_3'] = wp_strip_all_tags( $int_3 );
								}
								if( $int_4 ){
									$data['int_4'] = wp_strip_all_tags( $int_4 );
								}
								if( $int_5 ){
									$data['int_5'] = wp_strip_all_tags( $int_5 );
								}
								if( $int_6 ){
									$data['int_6'] = wp_strip_all_tags( $int_6 );
								}
								if( $int_7 ){
									$data['int_7'] = wp_strip_all_tags( $int_7 );
								}
								if( $int_8 ){
									$data['int_8'] = wp_strip_all_tags( $int_8 );
								}
								if( $int_9 ){
									$data['int_9'] = wp_strip_all_tags( $int_9 );
								}
								if( $int_10 ){
									$data['int_10'] = wp_strip_all_tags( $int_10 );
								}

								if( $note_1 ){
									$data['note_1'] = wp_strip_all_tags( $note_1 );
								}
								if( $note_2 ){
									$data['note_2'] = wp_strip_all_tags( $note_2 );
								}
								if( $note_3 ){
									$data['note_3'] = wp_strip_all_tags( $note_3 );
								}
								if( $note_4 ){
									$data['note_4'] = wp_strip_all_tags( $note_4 );
								}
								if( $note_5 ){
									$data['note_5'] = wp_strip_all_tags( $note_5 );
								}
								if( $note_6 ){
									$data['note_6'] = wp_strip_all_tags( $note_6 );
								}
								if( $note_7 ){
									$data['note_7'] = wp_strip_all_tags( $note_7 );
								}
								if( $note_8 ){
									$data['note_8'] = wp_strip_all_tags( $note_8 );
								}
								if( $note_9 ){
									$data['note_9'] = wp_strip_all_tags( $note_9 );
								}
								if( $note_10 ){
									$data['note_10'] = wp_strip_all_tags( $note_10 );
								}

								$data['last_update_at'] = date_i18n('Y-m-d H:i:s');

								/*$data = [
									'reference'					=>	wp_strip_all_tags( $reference ),
									'eth_address'				=>	wp_strip_all_tags( $eth_address ),
									'occurs_times'				=>	wp_strip_all_tags( $occurs_times ),
									'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
									'csramount_by_ethaddress'	=>	wp_strip_all_tags( $csramount_by_ethaddress ),
									'csr_amount_issued'			=>	wp_strip_all_tags( $csr_amount_issued ),
									'amount_due'				=>	wp_strip_all_tags( $amount_due ),
									'username'					=>	wp_strip_all_tags( $username ),
									'csramount_byusername'		=>	wp_strip_all_tags( $csramount_byusername ),
									'occurs_times_user'			=>	wp_strip_all_tags( $occurs_times_user ),
									'first_name'				=>	wp_strip_all_tags( $first_name ),
									'last_name'					=>	wp_strip_all_tags( $last_name ),
									'redemption_date'			=>	wp_strip_all_tags( $redemption_date_formatted ),
									'claim_date'				=>	wp_strip_all_tags( $claim_date_formatted ),
									'email'						=>	wp_strip_all_tags( $email ),
									'_user_status'				=>	wp_strip_all_tags( $user_status ),
									'kyc_status'				=>	wp_strip_all_tags( $kyc_status ),
									'pool_ref'					=>	wp_strip_all_tags( $pool_ref ),
									'approvedkyc'				=>	wp_strip_all_tags( $approvedkyc ),
									'corp_approved'				=>	wp_strip_all_tags( $corp_approved ),
									'notes_external'			=>	wp_strip_all_tags( wp_unslash( $notes_external ) ),
									'notes_internal'			=>	wp_strip_all_tags( wp_unslash( $notes_internal ) ),
									'position'					=>	wp_strip_all_tags( $position ),
									'text_1'					=>	wp_strip_all_tags( $text_1 ),
									'text_2'					=>	wp_strip_all_tags( $text_2 ),
									'text_3'					=>	wp_strip_all_tags( $text_3 ),
									'date_1'					=>	wp_strip_all_tags( $date_1 ),
									'date_2'					=>	wp_strip_all_tags( $date_2 ),
									'date_3'					=>	wp_strip_all_tags( $date_3 ),
									'int_1'						=>	wp_strip_all_tags( $int_1 ),
									'int_2'						=>	wp_strip_all_tags( $int_2 ),
									'int_3'						=>	wp_strip_all_tags( $int_3 ),
									'note_1'					=>	wp_strip_all_tags( $note_1 ),
									'note_2'					=>	wp_strip_all_tags( $note_2 ),
									'note_3'					=>	wp_strip_all_tags( $note_3 ),
									'last_update_at'			=>	date_i18n('Y-m-d H:i:s'),
								];*/
								$updating = $wpdb->update( $thTable, $data, $where );
								if( $updating ){
									$logs .= sprintf( $rowRawString, $trSuccess, $row, $reference, __('updated',CIP_TXTDOMAIN) );
									$log_msg = $row . ' :: ' . $reference . ' :: ' . __('updated',CIP_TXTDOMAIN);
									cip_create_logs( $log_msg );
								}else{
									$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('failed to update',CIP_TXTDOMAIN) );
									$log_msg = $row . ' :: ' . $reference . ' :: ' . __('failed to update',CIP_TXTDOMAIN);
									cip_create_logs( $log_msg );
								}
							}else{
								$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('not found for update',CIP_TXTDOMAIN) );
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('not found for update',CIP_TXTDOMAIN);
								cip_create_logs( $log_msg );
							}
						}
						$log_type = 'update_csv';
						$user = wp_get_current_user();
						create_cip_logs_entery( $user->ID, $log_type );
					}else{ //insert

						$getRefData = $wpdb->get_row("SELECT id FROM $thTable WHERE reference = '".$reference."' ");
						if( $getRefData ){
							$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('skipped, Duplicate entry found',CIP_TXTDOMAIN) );
							$log_msg = $row . ' :: ' . $reference . ' :: ' . __('skipped, Duplicate entry found',CIP_TXTDOMAIN);
								cip_create_logs( $log_msg );
								break;
						}else{
							$validationError = [];
							if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
								$rowError = true;
								$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
							}
							if( !empty( $occurs_times ) && !is_numeric( $occurs_times ) ){
								$rowError = true;
								$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $csramount_by_ethaddress ) && !is_numeric( $csramount_by_ethaddress ) ){
								$rowError = true;
								$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
								$rowError = true;
								$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $amount_due ) && !is_numeric( $amount_due ) ){
								$rowError = true;
								$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $csramount_byusername ) && !is_numeric( $csramount_byusername ) ){
								$rowError = true;
								$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $csr_amount_issued ) && !is_numeric( $csr_amount_issued ) ){
								$rowError = true;
								$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $occurs_times_user ) && !is_numeric( $occurs_times_user ) ){
								$rowError = true;
								$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
							}
							if( !empty( $redemption_date ) && DateTime::createFromFormat('d/n/y', $redemption_date) === false ){
								$rowError = true;
								$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
							}
							if( !empty( $claim_date ) && DateTime::createFromFormat('d/n/y', $claim_date) === false ){
								$rowError = true;
								$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
							}
							if( !empty( $position ) && !is_numeric( $position ) ){
								$rowError = true;
								$validationError[] = __('Position is not numeric',CIP_TXTDOMAIN);
							}
							if( $rowError === true ){
								$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, implode(', ', $validationError) );
								$log_msg = $row . ' :: ' . $reference . ' :: ' . implode(', ', $validationError);
								cip_create_logs( $log_msg );
								break;
								// continue;
							}
							$redemption_date_formatted = "";
							$claim_date_formatted = "";
							$formattedRDate = DateTime::createFromFormat('d/m/Y', $redemption_date);
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $claim_date);
							if( $formattedRDate ){
								$redemption_date_formatted = $formattedRDate->format('d/m/Y');
							}
							if( $formattedCDate ){
								$claim_date_formatted = $formattedCDate->format('d/m/Y');
							}
							$data = [
								'reference'					=>	wp_strip_all_tags( $reference ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'occurs_times'				=>	wp_strip_all_tags( $occurs_times ),
								'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
								'csramount_by_ethaddress'	=>	wp_strip_all_tags( $csramount_by_ethaddress ),
								'csr_amount_issued'			=>	wp_strip_all_tags( $csr_amount_issued ),
								'amount_due'				=>	wp_strip_all_tags( $amount_due ),
								'username'					=>	wp_strip_all_tags( $username ),
								'csramount_byusername'		=>	wp_strip_all_tags( $csramount_byusername ),
								'occurs_times_user'			=>	wp_strip_all_tags( $occurs_times_user ),
								'first_name'				=>	wp_strip_all_tags( $first_name ),
								'last_name'					=>	wp_strip_all_tags( $last_name ),
								'redemption_date'			=>	wp_strip_all_tags( $redemption_date_formatted ),
								'claim_date'				=>	wp_strip_all_tags( $claim_date_formatted ),
								'email'						=>	wp_strip_all_tags( $email ),
								'_user_status'				=>	wp_strip_all_tags( $user_status ),
								'kyc_status'				=>	wp_strip_all_tags( $kyc_status ),
								'pool_ref'					=>	wp_strip_all_tags( $pool_ref ),
								'approvedkyc'				=>	wp_strip_all_tags( $approvedkyc ),
								'corp_approved'				=>	wp_strip_all_tags( $corp_approved ),
								'notes_external'			=>	wp_strip_all_tags( wp_unslash( $notes_external ) ),
								'notes_internal'			=>	wp_strip_all_tags( wp_unslash( $notes_internal ) ),
								'position'					=>	wp_strip_all_tags( $position ),
								'text_1'					=>	wp_strip_all_tags( $text_1 ),
								'text_2'					=>	wp_strip_all_tags( $text_2 ),
								'text_3'					=>	wp_strip_all_tags( $text_3 ),
								'text_4'					=>	wp_strip_all_tags( $text_4 ),
								'text_5'					=>	wp_strip_all_tags( $text_5 ),
								'text_6'					=>	wp_strip_all_tags( $text_6 ),
								'text_7'					=>	wp_strip_all_tags( $text_7 ),
								'text_8'					=>	wp_strip_all_tags( $text_8 ),
								'text_9'					=>	wp_strip_all_tags( $text_9 ),
								'text_10'					=>	wp_strip_all_tags( $text_10 ),
								'date_1'					=>	wp_strip_all_tags( $date_1 ),
								'date_2'					=>	wp_strip_all_tags( $date_2 ),
								'date_3'					=>	wp_strip_all_tags( $date_3 ),
								'date_4'					=>	wp_strip_all_tags( $date_4 ),
								'date_5'					=>	wp_strip_all_tags( $date_5 ),
								'date_6'					=>	wp_strip_all_tags( $date_6 ),
								'date_7'					=>	wp_strip_all_tags( $date_7 ),
								'date_8'					=>	wp_strip_all_tags( $date_8 ),
								'date_9'					=>	wp_strip_all_tags( $date_9 ),
								'date_10'					=>	wp_strip_all_tags( $date_10 ),
								'int_1'						=>	wp_strip_all_tags( $int_1 ),
								'int_2'						=>	wp_strip_all_tags( $int_2 ),
								'int_3'						=>	wp_strip_all_tags( $int_3 ),
								'int_4'						=>	wp_strip_all_tags( $int_4 ),
								'int_5'						=>	wp_strip_all_tags( $int_5 ),
								'int_6'						=>	wp_strip_all_tags( $int_6 ),
								'int_7'						=>	wp_strip_all_tags( $int_7 ),
								'int_8'						=>	wp_strip_all_tags( $int_8 ),
								'int_9'						=>	wp_strip_all_tags( $int_9 ),
								'int_10'					=>	wp_strip_all_tags( $int_10 ),
								'note_1'					=>	wp_strip_all_tags( $note_1 ),
								'note_2'					=>	wp_strip_all_tags( $note_2 ),
								'note_3'					=>	wp_strip_all_tags( $note_3 ),
								'note_4'					=>	wp_strip_all_tags( $note_4 ),
								'note_5'					=>	wp_strip_all_tags( $note_5 ),
								'note_6'					=>	wp_strip_all_tags( $note_6 ),
								'note_7'					=>	wp_strip_all_tags( $note_7 ),
								'note_8'					=>	wp_strip_all_tags( $note_8 ),
								'note_9'					=>	wp_strip_all_tags( $note_9 ),
								'note_10'					=>	wp_strip_all_tags( $note_10 ),
								'imported_by'				=>	get_current_user_id(),
								'import_at'					=>	date_i18n('Y-m-d H:i:s'),
								'last_update_at'			=>	date_i18n('Y-m-d H:i:s'),
							];
							$inserting = $wpdb->insert( $thTable, $data );
							if( $inserting ){
								$logs .= sprintf( $rowRawString, $trSuccess, $row, $reference, __('inserted',CIP_TXTDOMAIN) );
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('inserted',CIP_TXTDOMAIN);
								cip_create_logs( $log_msg );
							}else{
								$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('failed',CIP_TXTDOMAIN) );
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('failed',CIP_TXTDOMAIN);
								cip_create_logs( $log_msg );
								break;
							}
						}
						$log_type = 'import_csv';
						$user = wp_get_current_user();
						create_cip_logs_entery( $user->ID, $log_type );
					}
				}
				if( !empty( $logs ) ){
					$logTable = '<style>.table-success tbody+tbody, .table-success td, .table-success th, .table-success thead th{border-color: #8fd19e;}.table-success, .table-success>td, .table-success>th{background-color: #84d897 !important;}.table-danger tbody+tbody, .table-danger td, .table-danger th, .table-danger thead th{border-color: #ed969e !important;}.table-danger, .table-danger>td, .table-danger>th{background-color: #f5c6cb !important;}</style><table class="table table-sm table-borderless">
								  <thead>
								    <tr>
								      <th scope="col">#</th>
								      <th scope="col">'.__('Reference',CIP_TXTDOMAIN).'</th>
								      <th scope="col">'.__('Log',CIP_TXTDOMAIN).'</th>
								    </tr>
								  </thead>
								  <tbody>';
					$logTable .= $logs;
					$logTable .= '</tbody>
								</table>';
				}
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'logs' => $logTable );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_enqueue_scripts', 'cip_enqueue_scripts_cb' );
function cip_enqueue_scripts_cb(){
	wp_enqueue_script('jquery', "//cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js", array(),'3.6.0', false);
	wp_enqueue_script('jquery.serializejson', plugin_dir_url( __FILE__ ). 'assets/jquery.serializejson.min.js', array( 'jquery' ),'3.2.1', false);
	wp_enqueue_script( 'bs-popper', '//cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js', array( 'jquery' ), '1.16.0', true );
	wp_enqueue_script( 'bs-js', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array( 'jquery' ), '4.3.1', true );
	wp_register_script( 'bs-table', plugin_dir_url( __FILE__ ). 'assets/bootstrap-table.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_script( 'bs-table-filter-control', plugin_dir_url( __FILE__ ).'assets/bootstrap-table-filter-control.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_script( 'bs-sticky-header', plugin_dir_url( __FILE__ ).'assets/bootstrap-table-sticky-header.min.js', array( 'jquery' ), '1.18.3', true );
	wp_register_style( 'bs-table', plugin_dir_url( __FILE__ ).'assets/bootstrap-table.min.css', array(), '1.18.3', 'all' );
	wp_register_style( 'bs-sticky-header', '//unpkg.com/bootstrap-table@1.18.3/dist/extensions/sticky-header/bootstrap-table-sticky-header.css', array(), '1.18.3', 'all' );
	wp_enqueue_style( 'bs-css', '//stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css', array(), '4.3.1', 'all' );
	wp_enqueue_style( 'global-cip-css', plugin_dir_url( __FILE__ ) . 'global-style.css', array(), time(), 'all' );
	wp_register_script( 'tbl-ex-js', '//cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/tableExport.min.js', array( 'jquery' ), '4.3.1', true );
	wp_register_script( 'jspdf', '//cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/jsPDF/jspdf.min.js', array( 'jquery' ), '4.3.1', true );
	wp_register_script( 'pdf-autotable-js', '//cdn.jsdelivr.net/npm/tableexport.jquery.plugin@1.10.21/libs/jsPDF-AutoTable/jspdf.plugin.autotable.js', array( 'jquery' ), '4.3.1', true );
	wp_enqueue_script('sweetalert', "https://cdn.jsdelivr.net/npm/sweetalert2@7.32.4/dist/sweetalert2.all.min.js", array('jquery'),false, false);
	wp_register_script( 'ex-js', '//unpkg.com/bootstrap-table@1.18.3/dist/extensions/export/bootstrap-table-export.min.js', array( 'jquery' ), '4.3.1', true );
	//bs datepicker
	wp_register_script('bs-datepicker', "//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js", array('jquery'),'1.9.0', false);
	wp_register_style('bs-datepicker', '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css');
	wp_register_style('cip-css', plugin_dir_url( __FILE__ ) . 'cip-style.css', array(), time(), 'all');
	//blockUI
	wp_enqueue_script( 'blockUI', '//cdnjs.cloudflare.com/ajax/libs/jquery.blockUI/2.70/jquery.blockUI.min.js', array(),'2.70' , true );
	wp_register_script( 'crypto-js', '//cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js', array(),'4.0.0' , false );
	wp_register_script('cip-abi', plugin_dir_url( __FILE__ ). 'cip-abi.js', '',time(), true);
	wp_register_script('cip-scripts', plugin_dir_url( __FILE__ ). 'cip-scripts.js', '',time(), true);
	wp_register_script('notify-js', "//cdnjs.cloudflare.com/ajax/libs/notify/0.4.2/notify.js", array(),'0.4.2', false);
	wp_enqueue_script('web3@latest', "//cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js", array(),'0.4.2', false);

	wp_register_script('jquery-ui', "//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js", array(),'1.12.1', false);
	wp_register_style('jquery-ui-style', "//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css", array(),'1.12.1', false);
	wp_register_script('jquery.inputmask', '//cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.8/jquery.inputmask.min.js', array('jquery'), '5.0.8', true);
	/* wp_register_style('magnify.css', "//cdnjs.cloudflare.com/ajax/libs/magnify/2.3.3/css/magnify.min.css", array(),'2.3.3', false);
	wp_register_script('magnify.js', '//cdnjs.cloudflare.com/ajax/libs/magnify/2.3.3/js/jquery.magnify.min.js', array('jquery'), '2.3.3', true); */

	// wp_register_script('jquery-ui-timepicker', "//cdn.jsdelivr.net/npm/jquery-ui-timepicker-addon@1.6.3/dist/jquery-ui-timepicker-addon.min.js", array(),'1.6.3', false);
	// wp_register_script('jquery-ui-sliderAccess', "//cdn.jsdelivr.net/npm/jquery-ui-timepicker-addon@1.6.3/dist/jquery-ui-sliderAccess.js", array(),'1.6.3', false);
	// wp_register_style('jquery-ui-timepicker-style', '//cdn.jsdelivr.net/npm/jquery-ui-timepicker-addon@1.6.3/dist/jquery-ui-timepicker-addon.css');
	//select2
	wp_register_script('select2', '//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js', array('jquery'), '4.1.0', true);
    wp_register_style('select2', '//cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css');

	//date range
	wp_register_script('dr-moment', '//cdn.jsdelivr.net/momentjs/latest/moment.min.js', array('jquery'), '1.0.0', true);
	wp_register_script('daterangepicker-script', '//cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js', array('jquery'), '1.0.0', true);
    wp_register_style('daterangepicker-style', '//cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css');

	//telephone picker
	wp_register_script('intlTelInput', '//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/18.2.1/js/intlTelInput.min.js', array('jquery'), '4.1.0', true);
    wp_register_style('intlTelInput', '//cdnjs.cloudflare.com/ajax/libs/intl-tel-input/18.2.1/css/intlTelInput.css');

	//magnify
	wp_register_script('magnify', plugin_dir_url( __FILE__ ).'assets/jquery.magnify.min.js', array('jquery'), '1.6.3', true);
    wp_register_style('magnify', plugin_dir_url( __FILE__ ).'assets/jquery.magnify.min.css');

	//tippy
	wp_register_script('tippy.popperjs', plugin_dir_url( __FILE__ ).'assets/tippy.popperjs.js', array('jquery'), '2.11.8', true);
	wp_register_script('tippy', plugin_dir_url( __FILE__ ).'assets/tippy.js', array('jquery'), '6.3.7', true);
	//js zip
	wp_register_script(
        'jszip',
        'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js',
        array(),
        '3.10.1',
        true
    );

	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
	$web3provider = ( $csr_wallet_api_mode == 'live' ) ? 'VHH03XzIO+b1N341d4FIw9PSFMDehQ0zFegIOpZP9G3IzFBELJuW5BN1iXr0sc+CJ7w3ds1N+jq10+QSTlza2A==' : 'AF1aOe9IKjDhtjniya9Zk/NpCjSNkqlgb1wF/64BJ94S52wlHHEWOkhjmAh+UvmN2lE9RmbL9O7Gr+f90y4Hzw==';
	$localize_string = array(
		'cipEncki'		=>  'c419c4b7724aab6ce4050d6722d20919',
		'cipEncvct'		=>  '53e38f43ad9e361e',
		'web3provider'	=>	$web3provider,
	);
	wp_localize_script( 'crypto-js', 'cryptojs', $localize_string );
	wp_enqueue_script('crypto-js');
	// var DataEncrypt = "6iip60g9u5DeUHvaJUR+W5ceHCOmMX5MsA0aTu73caKDNiHs4+yVD4HaZJm0nzLuxrjV8mgptWIU1MoDgr690w=="; rinkeby
	// var DataEncrypt = "VW0k6zOoKNehXstKs24IIPWVqqPoLPjgy4L2k3zHoCK/0rcmQ2+lW52mK3E+2c74f3Ky79U8NK5dDKwb8Sps1A=="; goerli
	// var DataEncrypt = "AF1aOe9IKjDhtjniya9Zk/NpCjSNkqlgb1wF/64BJ94S52wlHHEWOkhjmAh+UvmN2lE9RmbL9O7Gr+f90y4Hzw=="; sepolia

	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$tcCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");
	$tableMIName = $wpdb->prefix.'cip_member_invoice';
	$miCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableMIName");
	$incCsr = ( !empty( get_option('selling_price_csr_inc') ) ) ? get_option('selling_price_csr_inc') : 8;
	$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
	if($hall_of_fame_price_type == 'csr'){
		$selling_price_csr = ( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
	}else{
		$selling_price_csr = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
	}
	$selling_kgs = ( !empty( get_option('selling_kgs') ) ) ? get_option('selling_kgs') : 1;

	// $valTxt="https://mainnet.infura.io/v3/d2ffd9f21b584ff8ad185427a0421a1c";
	// $valTxt="https://rinkeby.infura.io/v3/161e66f35f0e461ca450b114bd1e4626";
	// $valTxt="https://sepolia.infura.io/v3/161e66f35f0e461ca450b114bd1e4626";

	$key="c419c4b7724aab6ce4050d6722d20919";
	$vector="53e38f43ad9e361e";

	$microGetAdrsData = [ 'action' => 'get_csraddress_act','_micro' => wp_create_nonce( '_XyGetEthAddressCSRyX_' ) ];
	$microGetAdrsDataSigned = [ 'action' => 'get_csraddress_sign_act','_micro' => wp_create_nonce( '_XyGetEthAddressSignCSRyX_' ) ];
	$microRetirementData = [ 'action' => 'csr_retirement_process_act','_micro' => wp_create_nonce( '_XyCsrRetirementProcessyX_' ) ];
	$microRetirementDataView = [ 'action' => 'csr_retirement_view_act','_micro' => wp_create_nonce( '_XyCsrRetirementViewyX_' ) ];
	$microRetirementUpdate = [ 'action' => 'csr_retirement_update_act','_micro' => wp_create_nonce( '_XyCsrRetirementUpdateyX_' ) ];
	$microUnSaveData = [ 'action' => 'cip_cancelsaveplan_act','_micro' => wp_create_nonce( '_XyUnSavePlanyX_' ) ];
	$microAllUnSaveData = [ 'action' => 'cip_cancelsaveplan_all_act','_micro' => wp_create_nonce( '_XyUnSaveAllPlanyX_' ) ];
	$microUnVerifyData = [ 'action' => 'cip_sa_unverifyaddress_act','_micro' => wp_create_nonce( '_XyUnVerifyEthX_' ) ];
	$microGetAllToggle = [ 'action' => 'cip_get_all_save_csr_amount','_micro' => wp_create_nonce( '_XyGetAllCsrCoinyX_' ) ];
	$microGetAllRetireToggle = [ 'action' => 'cip_get_all_retire_csr_amount','_micro' => wp_create_nonce( '_XyGetAllRetireCsrCoinyX_' ) ];
	$micrommtrans = wp_create_nonce( '_XyMmSaveTransHashyX_' );
	$micrommretire = wp_create_nonce( '_XyMmSaveTransRetireyX_' );
	$microschedulardel = wp_create_nonce( '_XyPendingSchedularDeleteyX_' );
	$tableDistribution = $wpdb->prefix.'token_holder_distribution';
	$getDistributions = $wpdb->get_var("SELECT COUNT(id) FROM $tableDistribution WHERE `append_status` = 1");
	$isDistributionData = ( $getDistributions > 0 ) ? 1 : 0;

	$tableDistributionTemp = $wpdb->prefix.'token_holder_distribution_temp';
	$getDistributionsTemp = $wpdb->get_var("SELECT COUNT(id) FROM $tableDistributionTemp WHERE `append_status` != 1");
	$isDistributionDataTemp = ( $getDistributionsTemp > 0 ) ? 1 : 0;

	$tableWeeklyDistribution = $wpdb->prefix.'weekly_distribution_export';
	$getWeeklyDistributions = $wpdb->get_var("SELECT COUNT(id) FROM $tableWeeklyDistribution WHERE `append_status` = 1");
	$isWeeklyDistributionData = ( $getWeeklyDistributions > 0 ) ? 1 : 0;
	$actionApprovedLogoUrl = [ 'action' => 'cip_approved_logourl_act','_micro' => wp_create_nonce( '_XyApprovedLogoUrlyX_' ) ];
	$actionRejectLogoUrl = [ 'action' => 'cip_reject_logourl_act','_micro' => wp_create_nonce( '_XyRejectLogoUrlyX_' ) ];
	$actionUpapproveLogoUrl = [ 'action' => 'cip_unapprove_logourl_act','_micro' => wp_create_nonce( '_XyUnApproveLogoUrlyX_' ) ];
	//4966
	$actionValidateAddCsrWalletData = [ 'action' => 'getValidateAddCsrWalletDataAct','_micro' => wp_create_nonce( '_XyValidateAddCsrWalletDatayX_' ) ];
	$actionApprovedCsrAddress = [ 'action' => 'cip_approved_csraddress_act','_micro' => wp_create_nonce( '_XyApprovedCsrAddressyX_' ) ];
	$actionRejectCsrAddressUrl = [ 'action' => 'cip_reject_csraddress_act','_micro' => wp_create_nonce( '_XyRejectCsrAddressyX_' ) ];
	$actionUpapproveLogoUrl = [ 'action' => 'cip_unapprove_logourl_act','_micro' => wp_create_nonce( '_XyUnApproveLogoUrlyX_' ) ];
	$actionApprovedCsrAddressLsh = [ 'action' => 'cip_approved_lsh_csraddress_act','_micro' => wp_create_nonce( '_XyApprovedLSHCsrAddressyX_' ) ];
	$actionRejectCsrAddressLsh = [ 'action' => 'cip_reject_lsh_csraddress_act','_micro' => wp_create_nonce( '_XyRejectLSHCsrAddressyX_' ) ];

	//5747
	$actionEnableCountriesAct = [ 'action' => 'cip_actionEnableCountries_act','_micro' => wp_create_nonce( '_XyEnableCountriesyX_' ) ];
	//5927
	$actionValidateAddNewCsrWalletData = [ 'action' => 'getValidateAddNewCsrWalletDataAct','_micro' => wp_create_nonce( '_XyValidateAddNewCsrWalletDatayX_' ) ];
	//5690
	$tableKyc = $wpdb->prefix.'kyc_data';
	$current_user = wp_get_current_user();
	$kycStep = 0;
	$getKycCurrentStep = $wpdb->get_row("SELECT `id`, `email`, `current_step`, `status`, `reject_steps` FROM $tableKyc WHERE `email` = '". $current_user->user_email ."'");
	if( $getKycCurrentStep ){
		if( $getKycCurrentStep->status == 'dropped' ){
			// $kycStep = ( $getKycCurrentStep->current_step >= 0 && $getKycCurrentStep->current_step <= 4 ) ? $getKycCurrentStep->current_step : 0;
			$kycStep = 0;
		}else if( $getKycCurrentStep->status == 'reject' ){
			/* $kycStepArr = ( !empty( $getKycCurrentStep->reject_steps ) ) ? explode(",", $getKycCurrentStep->reject_steps) : array($getKycCurrentStep->current_step);
			$kycStep = min( $kycStepArr );
			$kycStep = ( !empty( $getKycCurrentStep->current_step ) && $getKycCurrentStep->current_step < $kycStep ) ? $getKycCurrentStep->current_step : $kycStep; */
			$kycStep = 0;
		}else{
			$kycStep = ( $getKycCurrentStep->current_step >= 0 && $getKycCurrentStep->current_step <= 4 ) ? $getKycCurrentStep->current_step : 0;
		}
	}
	//5753
	$actionResetSA2FaAuth = [ 'action' => 'cip_reset_sa_2faauth_act','_micro' => wp_create_nonce( '_XyResetSupportAgent2FaAuthyX_' ) ];
	$withdrawal_request_wizard_process_current_step = get_option( 'withdrawal_request_wizard_process_current_step' );
	$withdrawRequestStep = ( !empty( $withdrawal_request_wizard_process_current_step ) && $withdrawal_request_wizard_process_current_step <= 3 ) ? $withdrawal_request_wizard_process_current_step : 0;
	$csr_retirement_banner_initial_delay = ( !empty( get_option('csr_retirement_banner_initial_delay') ) ) ? get_option('csr_retirement_banner_initial_delay') : 60 ;
	$csr_retirement_banner_interval = ( !empty( get_option('csr_retirement_banner_interval') ) ) ? get_option('csr_retirement_banner_interval') : 300 ;
	$csr_retirement_banner_display_time = ( !empty( get_option('csr_retirement_banner_display_time') ) ) ? get_option('csr_retirement_banner_display_time') : 3 ;

	$tableNewDeliveryPlanTemp = $wpdb->prefix.'new_delivery_plan_temp';
	$getNewDeliveryPlanDistributions = $wpdb->get_var("SELECT COUNT(id) FROM $tableNewDeliveryPlanTemp WHERE `append_status` = 1");
	$isNewDeliveryPlanDistributionData = ( $getNewDeliveryPlanDistributions > 0 ) ? 1 : 0;

	global $post;
	$localize_string = array(
		'ajax_url' 			=> admin_url( 'admin-ajax.php'),
		'site_url' 			=> site_url(),
		'_microsmco'		=> wp_create_nonce('_XyUpdateColumnOrderyX_'),
		'_microvsign'		=> wp_create_nonce('_XyVerfySignatureyX_'),
		'_microgeteth'		=> wp_create_nonce('_XyGetUserEthyX_'),
		'alltcnum'			=> $tcCount,
		'allminum'			=> $miCount,
		'incCsr'			=> $incCsr,
		'selling_price'		=> $selling_price_csr,
		'selling_kgs'		=> $selling_kgs,
		'tokenaddress'		=> $contractaddress,
		'csrapi_mode'		=> $csr_wallet_api_mode,
		'microGetAdrsData'	=> $microGetAdrsData,
		'microGetAdrsSignData'	=> $microGetAdrsDataSigned,
		'microRetirementData'	=> $microRetirementData,
		'microRetirementDataView'	=> $microRetirementDataView,
		'microRetirementUpdate'	=> $microRetirementUpdate,
		'microUnSaveData'	=> $microUnSaveData,
		'microAllUnSaveData'	=> $microAllUnSaveData,
		'microUnVerifyData'	=> $microUnVerifyData,
		'microGetAllToggle'	=> $microGetAllToggle,
		'microGetAllRetireToggle'	=> $microGetAllRetireToggle,
		'micrommtrans'	=> $micrommtrans,
		'microGetAllRetireToggle'	=> $microGetAllRetireToggle,
		'micrommretire'	=> $micrommretire,
		'microschedulardel'	=> $microschedulardel,
		'actionApprovedLogoUrl'	=> $actionApprovedLogoUrl,
		'actionRejectLogoUrl'	=> $actionRejectLogoUrl,
		'actionUpapproveLogoUrl'	=> $actionUpapproveLogoUrl,
		'isDistributionData'	=> $isDistributionData,
		'isDistributionDataTemp'	=> $isDistributionDataTemp,
		'isWeeklyDistributionData'	=> $isWeeklyDistributionData,
		'current_page'	=> get_permalink(),
		'actionValidateAddCsrWalletData'	=> $actionValidateAddCsrWalletData,
		'actionRejectCsrAddressUrl'	=> $actionRejectCsrAddressUrl, //4966
		'actionApprovedCsrAddress'	=> $actionApprovedCsrAddress, //4966
		'actionApprovedCsrAddressLsh'	=> $actionApprovedCsrAddressLsh, //4966
		'actionRejectCsrAddressLsh'	=> $actionRejectCsrAddressLsh, //4966
		'kycStep'	=> $kycStep, //5690
		'kycVerificationUrl'	=>	get_the_permalink( get_page_by_path('kyc-verification') ),
		'cip_images_folder'	=>	CIP_PLUGIN_FOLDER . '/images/',
		'actionEnableCountriesAct'	=> $actionEnableCountriesAct, //5747
		'actionResetSA2FaAuthAct'	=> $actionResetSA2FaAuth, //5753
		'withdrawRequestStep'	=> $withdrawRequestStep, //5753
		'retirement_banner_initial_delay'	=> $csr_retirement_banner_initial_delay,
		'retirement_banner_interval'	=> $csr_retirement_banner_interval,
		'retirement_banner_display_time'	=> $csr_retirement_banner_display_time,
		'actionValidateAddNewCsrWalletData'	=> $actionValidateAddNewCsrWalletData,
		'currentPage'	=>	$post->ID,
		'isUserSM'	=>	( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ? 1 : 0,
		'isNewDeliveryPlanDistributionData'	=> $isNewDeliveryPlanDistributionData,
	);
	wp_localize_script( 'cip-scripts', 'cipscript', $localize_string );
	wp_enqueue_script('cip-scripts');
}
function myCrypt($value, $key, $iv){
    $encrypted_data = openssl_encrypt($value, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
    return base64_encode($encrypted_data);
}
// add_action('wp_footer','test_key_url_print');
function test_key_url_print(){
	// echo myCrypt('https://mainnet.infura.io/v3/d2ffd9f21b584ff8ad185427a0421a1c','c419c4b7724aab6ce4050d6722d20919','53e38f43ad9e361e');
	// echo myCrypt('https://goerli.infura.io/v3/161e66f35f0e461ca450b114bd1e4626','c419c4b7724aab6ce4050d6722d20919','53e38f43ad9e361e');
	// echo myCrypt('https://sepolia.infura.io/v3/28db03efbc5b42839ebb7d5965c1748d','c419c4b7724aab6ce4050d6722d20919','53e38f43ad9e361e');
}
add_action('init', 'cip_startsession', 20);
function cip_startsession(){
	if(!session_id()){
		@session_start();
    }
}
function cip_create_logs( $message = "", $faildlog = false ){
	$user_id = get_current_user_id();
	if( $faildlog == true ){
		$filename = $user_id . '_' . 'cip_import_faild.log';
	}else{
		$filename = $user_id . '_' . 'cip_import.log';
	}
	$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a");
	fwrite($file, $message . "\n");
	fclose($file);
}
function cip_clear_logs(){
	$user_id = get_current_user_id();
	$filename = $user_id . '_' . 'cip_import.log';
	$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"w");
	fclose($file);
	$filename = $user_id . '_' . 'cip_import_faild.log';
	$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"w");
	fclose($file);
}
add_action('wp_footer','cip_init_bs_table_script');
function cip_init_bs_table_script(){
	// update_option('last_weekly_distribution', '' );
	$pagingUrlData = array();
	$pagingUrlData['action'] = 'retirement_loader';
	$pagingUrlData['pageid'] = get_the_ID();
	$data_url = add_query_arg( $pagingUrlData, admin_url( 'admin-ajax.php' ) );
	$holderRetireData = array();
	$holderRetireData['action'] = 'holder_retirement_loader';
	$holderRetireData['eth_address'] = ( isset( $_GET['address'] ) && !empty( $_GET['address'] ) ) ? $_GET['address'] : '-';
	$holderRetireUrl = add_query_arg( $holderRetireData, admin_url( 'admin-ajax.php' ) );

	$euvatapiLogsData = array();
	$euvatapiLogsData['action'] = 'euvatapi_logs_loader';
	$euvatapiLogsData['pageid'] = get_the_ID();
	$euvatapiLogsUrl = add_query_arg( $euvatapiLogsData, admin_url( 'admin-ajax.php' ) );
	$walletapiLogsData = array();
	$walletapiLogsData['action'] = 'wallet_api_logs_loader';
	$walletapiLogsUrl = add_query_arg( $walletapiLogsData, admin_url( 'admin-ajax.php' ) );
?><script>
	jQuery(window).on('load', function(){
		if(jQuery('#gform_4 .order-summary').length > 0){
			const formData = <?php echo json_encode($_POST); ?>;
			const buyerName = `${formData['input_1_3'] || ''} ${formData['input_1_6'] || ''}`.trim();
			const businessName = formData['input_2'] || '';
			const street_address = formData['input_5_1'] || '';
			const address = formData['input_5_2'] || '';
			const city = formData['input_5_3'] || '';
			const province = formData['input_5_4'] || '';
			const postalCode = formData['input_5_5'] || '';
			const country = formData['input_5_6'] || '';
			const plasticNeutralityPackage = formData['input_16'] || '0.00';
			const taxes = formData['input_33'] || '0.00';
			const totalPayable = (parseFloat(plasticNeutralityPackage) + parseFloat(taxes)).toFixed(2);
			<?php 
				$price = $_POST['input_16'];
				$vat = $_POST['input_33'];
				$vat_rate = null;
				$POVATPercentage = null;
				$VATPercentage = null;
				$countryCode = GF_Fields::get( 'address' )->get_country_code( $_POST['input_5_6'] );
				if( !empty( $vat ) && $countryCode == 'EE' ){
					$vat_rate = 22;
				}else if( !empty( $vat ) && isEU( $countryCode ) ){
					$vat_rate = 0;
					$POVATPercentage = "Reverse-Charge";
					$VATPercentage = "Reverse-Charge";
				}else if( !empty( $vat ) && $countryCode == 'GB' ){
					$vat_rate = 0;
				}else if( empty( $vat ) ){
					$euvatapi_ip_address = ( !empty( get_option('euvatapi_ip_address') ) ) ? get_option('euvatapi_ip_address') : '';
					if( !empty( $euvatapi_ip_address ) ){
						$ip_address = $euvatapi_ip_address;
					}else{
						$ip_address = cip_get_client_ip();
					}
					// $vatRateResponse = get_vat_rate_ipaddress_api_callback( $ip_address );
					$vatRateCountryResponse = get_vat_rate_code_api_callback( $countryCode );
					
					if( $vatRateCountryResponse['success'] ){
						$vat_rate = $vatRateCountryResponse['standard_rate'];
						$responseCountry = $vatRateCountryResponse['country_code'];
						if( $responseCountry == 'EE' ){
							$vat_rate = 22;
						}else if( $responseCountry == 'GB' ){
							$vat_rate = 0;
						}
					}
				}
				if( is_null( $POVATPercentage ) ){
					$POVATPercentage = $vat_rate;
				}
				if( is_null( $VATPercentage ) ){
					$VATPercentage = $vat_rate;
				}
				
				$NetAmount = $price + ( ( $price * $vat_rate ) / 100 );
				$VATAmount = $NetAmount - $price;
			?>
			$('#gform_4 .order-summary #buyer_name').text(buyerName);
			$('#gform_4 .order-summary #street_address').text(street_address);
			$('#gform_4 .order-summary #city').text(city);
			$('#gform_4 .order-summary #province').text(province);
			$('#gform_4 .order-summary #postal_code').text(postalCode);
			$('#gform_4 .order-summary #country').text(country);
			$('#gform_4 .order-summary #plastic_Neutrality_package').text( addCommas( parseFloat(plasticNeutralityPackage).toFixed(2) ) );
			$('#gform_4 .order-summary #taxes').text( addCommas( parseFloat(<?php echo $VATAmount; ?>).toFixed(2) ) );
			$('#gform_4 .order-summary #total_payable').text( addCommas( parseFloat(<?php echo $NetAmount; ?>).toFixed(2) ) );
			if (businessName === '' || businessName.trim() === '') {
				$('#gform_4 .order-summary #business_name').closest('.form-get-data').remove();
			} else {
				$('#gform_4 .order-summary #business_name').text(businessName);
			}
			if (address === '' || address.trim() === '') {
				$('#gform_4 .order-summary #address').closest('.form-get-data').remove();
			} else {
				$('#gform_4 .order-summary #address').text(address);
			}

		}
	});
jQuery(document).ready(function($){
  	var sathpage = "<?php echo get_the_permalink(); ?>";
  	var ajax_url = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
	var data_url = "<?php echo $data_url ?>";
	if( $('#tokenholder_table').length > 0 ){
		var $tableTH = $('#tokenholder_table');
		$tableTH.bootstrapTable({
			stickyHeader: false,
			// stickyHeaderOffsetY: parseInt($('header').height()),
			/*theadClasses: classes, */
			onPostBody: function (){
				if( $('body').find('.modelpop_notes').length > 0 ){
					// console.log('test');
					$('[data-toggle-tt="tooltip"]').tooltip();
				}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
		  	}
		});
		$('#toolbar').find('select').change(function () {
		$tableTH.bootstrapTable('destroy').bootstrapTable({
			stickyHeader: false,
			// stickyHeaderOffsetY: parseInt($('header').height()),
			exportDataType: $(this).val(),
			  exportTypes: ['csv','pdf'],
			  columns: [
				{
				  field: 'state',
				  checkbox: true,
				  visible: $(this).val() === 'selected'
				},
				{
				  field: 'id',
				  title: 'id'
				}, {
				  field: 'type',
				  title: 'type'
				}, {
				  field: 'status',
				  title: 'status'
				}
			  ]
			});
		});
	}
	if( $('#tokenholder_table_retirment').length > 0 ){
		var $tableTHRetirment = $('#tokenholder_table_retirment');
		$tableTHRetirment.bootstrapTable({
			stickyHeader: false,
			// stickyHeaderOffsetY: parseInt($('header').height()),
			/*theadClasses: classes, */
			onPostBody: function (){
				if( $('body').find('.modelpop_notes').length > 0 ){
					// console.log('test');
					$('[data-toggle-tt="tooltip"]').tooltip();
				}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
		  	}
		});
	}
	if( $('#cip_sasm_table').length > 0 ){
		var $tablesasm = $('#cip_sasm_table');
		$tablesasm.bootstrapTable({
			stickyHeader: true,
			// stickyHeaderOffsetY: parseInt($('header').height()),
		});
	}
	if( $('.filter_area .input-daterange').length > 0 ){
		$('.filter_area .input-daterange').datepicker({
			format: 'dd/mm/yyyy',
			autoclose: true,
		});
	}
	if( $('#sa_member_update #redemption_date').length > 0 ){
		$('#sa_member_update #redemption_date, #sa_member_update #claim_date').datepicker({
			format: 'dd/mm/yyyy',
			autoclose: true,
		});
	}
	if( $('#sa_member_update #date_of_claim').length > 0 ){
		$('#sa_member_update #date_of_claim, #sa_member_update #registration_date').datepicker({
			format: 'dd-mm-yyyy',
			autoclose: true,
		});
	}
	var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
	$("body").on("submit","#sa_member_update",function(){
		var data = $(this).serialize();
		if( $('#update_all_match:checked').val() == 1 ){
			if( $('#update_all_option').val() == 'all_reference_update' ){
				if( $('#reference_update_field').val() == "" ){
					$('.form_response').html( 'Reference is required' );
					swalToast({ type: 'error', title: 'Reference is required' });
					return false;
				}
			}
		}
		var sm_editth_ga_otp = $(this).find('input[name="sm_editth_ga_otp"]').val();
		if( sm_editth_ga_otp == "" ){
			swalToast({ type: 'error', title: 'Please enter the authentication code' });
			return false;
		}
		// $('#sa_member_update').block( block_config );
		$.blockUI( block_config );
		$.post(ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$('#sa_member_update').unblock();
			//console.log( obj );
			if( obj.error == 0 ){
				window.location.href = sathpage;
				swalToast({ type: 'success', title: obj.msg });
				$('#smEditTokenHolderG2FAModal').modal('hide');
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
			$('.form_response').html( obj.msg );
			$.unblockUI();
		});
		return false;
	});
	//MA enable form script
	$("body").on("submit","#ma_member_update",function(){
		var data = $(this).serialize();
		if( $('#update_all_match:checked').val() == 1 ){
			if( $('#update_all_option').val() == 'all_reference_update' ){
				if( $('#reference_update_field').val() == "" ){
					$('.form_response').html( 'Reference is required' );
					return false;
				}
			}
		}
		$('#ma_member_update').block( block_config );
		$.post(ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$('#ma_member_update').unblock();
			console.log( obj );
			if( obj.error == 0 ){
				window.location.href = sathpage;
			}
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	$("body").on("submit","#smsa_update_usr",function(){
		var data = $(this).serialize();
		$('#smsa_update_usr').block( block_config );
		$.post(ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$('#smsa_update_usr').unblock();
			/*if( obj.error == 0 ){
				window.location.href = sathpage;
			}*/
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	$("body").on("submit","#smsaown_update_usr",function(){
		var data = $(this).serialize();
		$('#smsaown_update_usr').block( block_config );
		$.post(ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$('#smsaown_update_usr').unblock();
			/*if( obj.error == 0 ){
				window.location.href = sathpage;
			}*/
			$('.form_response').html( obj.msg );
		});
		return false;
	});
	$('body').on('click','.delete_sath', function(){
		if( confirm("Are you sure want to delete?") === true ){
			var thisId = $(this).attr('data-id');
			var data = {'action':'sa_delth_act','sathid':thisId};
			$.post(ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				alert( obj.msg );
				if( obj.error == 0 ){
					window.location.href = sathpage;
				}
			});
		}
	});
	$('body').on('change','select[name="update_smsa"]', function(){
		var thisId = $(this).attr('data-uid');
		var thisVal = $(this).val();
		var blockElem = $(this).closest('tr');
		var data = {'action':'sasm_updatestatus_act','cipthisid':thisId,'cipthisval':thisVal};
		blockElem.block( block_config );
		$.post(ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			blockElem.unblock();
		});
	});
	window.BsTableFilterStatus = function (text, value, field, data){
	   if( text.toLowerCase() === value.toLowerCase() ){
	   		return true;
	   }else{
	   		return false;
	   }
	}
	if( $('#cip_saving_plans_table').length > 0 ){
		var $tableSP = $('#cip_saving_plans_table');
		$tableSP.bootstrapTable({
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
		  	}
		});
	}
	if( $('#holders_retirement_table').length > 0 ){
		var $retirementTable = $('#holders_retirement_table');
		var holderRetireUrl = "<?php echo $holderRetireUrl ?>";
		$retirementTable.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: holderRetireUrl,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
			// stickyHeaderOffsetY: parseInt($('header').height()),
			onPostBody: function (){
				if( $('body').find('.modelpop_notes').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
		  	}
		});
	}
	if( $('#euvatapi_logs_table').length > 0 ){
		var euvatapi_logs_table = $('#euvatapi_logs_table');
		var euvatapiLogsUrl = "<?php echo $euvatapiLogsUrl; ?>";
		euvatapi_logs_table.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: euvatapiLogsUrl,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
			// stickyHeaderOffsetY: parseInt($('header').height()),
			onPostBody: function (){

		  	}
		});
	}
	if( $('#cip_logs_table').length > 0 ){
		var cip_logs_table = $('#cip_logs_table');
		var walletapiLogsUrl = "<?php echo $walletapiLogsUrl; ?>";
		var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
		cip_logs_table.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: walletapiLogsUrl,
			searchOnEnterKey: true,
			queryParams: function (p) {
				filterByConditionPoolRef = convertFormToJSON( '#filter_by_logs' );
				$.blockUI(block_config);
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					'filterByConditionPoolRef': filterByConditionPoolRef,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
			//stickyHeaderOffsetY: parseInt($('header').height()),
			onPostBody: function (){
				$.unblockUI();
			},
			onPreBody: function () {
				// Show loader
				$.blockUI(block_config);
			},
			onLoadSuccess: function () {
				// Hide loader data success
				$.unblockUI();
			},
			onLoadError: function () {
				// Hide loader on error
				$.unblockUI();
			}
		});
	}
	if( $('#schedule_time').length > 0 ){
		$('#schedule_time').datepicker({
			dateFormat: 'dd/mm/yy',
			minDate:0,
			// timezone:'0',
			/*beforeShow: function () {
				var nowClick = setInterval(function(){
					console.log( $('#schedule_time').val() );
					if( $('#schedule_time').val() == "" ){
						$('body').find('.ui-datepicker-current').trigger('click');
						clearInterval(nowClick);
					}
				}, 1000);
			},
			onSelect: function(dateText, inst) {
				var picker = $('#schedule_time').data('datetimepicker');
				// var picker = $('#schedule_time').val();
				console.log( picker );
				var convertDateTime = convertToUtc( picker );
				// $('#schedule_time').val( convertDateTime );
				$('#schedule_time_alt').val( convertDateTime );
			},*/
			altField: "#schedule_time_alt",
			altFormat: "yy-mm-dd",
		}).attr('readonly', 'readonly');
	}
	function convertToUtc(str) {
        return moment(str).utc().format('YYYY-MM-DD HH:mm');
	}
});
</script>
<?php
}
add_action('wp_ajax_sa_update_th_tp1_act','sa_update_th_tp1_act_cb');
function sa_update_th_tp1_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_Xupdatethtp1X_' ) ){
		global $wpdb;
		global $defaultColumnsArr;
		$tableName = $wpdb->prefix.'token_holder';
		$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( $google_auth_key ) ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( empty( $_POST['sm_editth_ga_otp'] ) ){
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$google2fa = new \PragmaRX\Google2FA\Google2FA();
		if( $google2fa->verifyKey($google_auth_key, $_POST['sm_editth_ga_otp'], 0) ){
			if( isset( $_POST['update_all_match'] ) && $_POST['update_all_match'] == 1 && $_POST['update_all_option'] != 'single_row_update' ){ //condition based update

				if( $_POST['update_all_option'] == 'all_username_update' || $_POST['update_all_option'] == 'all_email_update' || $_POST['update_all_option'] == 'all_reference_update' || $_POST['update_all_option'] == 'all_wallet_address_update' ){
					$data = array();
					$validationError = [];
					$rowError = false;
					if( $_POST['update_all_option'] == 'all_username_update' ){
						unset( $defaultColumnsArr['username'] );
					}else if( $_POST['update_all_option'] == 'all_email_update' ){
						unset( $defaultColumnsArr['email'] );
					}else if( $_POST['update_all_option'] == 'all_reference_update' ){
						unset( $defaultColumnsArr['reference'] );
					}else if( $_POST['update_all_option'] == 'all_wallet_address_update' ){
						unset( $defaultColumnsArr['eth_address'] );
					}
					$checkOgData = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['sathid']."");
					foreach( $defaultColumnsArr as $columnKey => $columnLbl ){

						if( $checkOgData->$columnKey != $_POST[ $columnKey ] && ( !empty( $checkOgData->$columnKey ) || !empty( $_POST[ $columnKey ] ) ) ){
							//continue for update
						}else{
							//continue for skip
							continue;
						}
						if( $columnKey == 'email' && isset( $_POST[ $columnKey ] ) && !filter_var($_POST[ $columnKey ], FILTER_VALIDATE_EMAIL) ){
							$rowError = true;
							$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'occurs_times' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'csramount_by_ethaddress' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'csr_amount_initial' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'amount_due' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'csramount_byusername' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'csr_amount_issued' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'occurs_times_user' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'redemption_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
							$rowError = true;
							$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'claim_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
							$rowError = true;
							$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
						}
						if( $columnKey == 'position' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
							$rowError = true;
							$validationError[] = __('Position is not numeric',CIP_TXTDOMAIN);
						}
						if( isset( $_POST[ $columnKey ] ) ){
							$data[ $columnKey ] = wp_unslash( $_POST[ $columnKey ] );
						}
					}
					// echo wp_json_encode( $data );
					// exit;
					if( $rowError === true ){
						$out = array( "error" => 1,'msg' => implode(', ', $validationError) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $_POST['update_all_option'] == 'all_username_update' ){ //by username update
						$checkUsername = $wpdb->get_row("SELECT username FROM $tableName WHERE id = ".$_POST['sathid']."");
						if( isset( $_POST['username'] ) ){
							if( $checkUsername->username == $_POST['username'] ){
								$updateingToggleValue = false;
								if( isset( $_POST['username'] ) && !empty( $_POST['username'] ) ){
									$getUpdateEmailData = $wpdb->get_row("SELECT `email` FROM $tableName WHERE `id`=".$_POST['sathid']."");
									$getRecordsByusername = $wpdb->get_results("SELECT * FROM $tableName WHERE `username`='". $_POST['username'] ."'");
									if( $getRecordsByusername ){
										foreach( $getRecordsByusername as $getRecordByusername ){
											$where = [ 'id' => $getRecordByusername->id ];
											$data['last_update'] = date_i18n('Y-m-d H:i:s');

											//exclude Issued and Delivered status to update when change status to hold or security hold
											$holdStatusArray = array( 'Hold', 'Security Hold' );
											$issuedStatusArray = array( 'Issued', 'Delivered' );
											if( isset( $_POST['corp_approved'] ) && in_array( $_POST['corp_approved'], $holdStatusArray ) ){ //check is hold or security hold status
												if( in_array(  $getRecordByusername->corp_approved, $issuedStatusArray ) ){	//check already have issued or delivered status
													$updatingData = $data;
													unset( $updatingData['corp_approved'] );
												}else{
													$updatingData = $data;
												}
											}else{
												$updatingData = $data;
											}

											$updating = $wpdb->update( $tableName, $updatingData, $where );
											if( $updating ){
												$updateingToggleValue = true;
												$updateRowEmail = "";
												$updatedData = array();
												if( $getRecordByusername ){
													$updateRowEmail = "updated holder by username(".$_POST['username'].") at ".date_i18n('d/m/Y H:i A').". ";
													foreach( $updatingData as $columnKey => $columnLbl ){
														if( isset( $_POST[ $columnKey ] ) ){
															if( $getRecordByusername->$columnKey != $_POST[ $columnKey ] ){
																$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getRecordByusername->$columnKey, $_POST[ $columnKey ] );
															}
														}
													}
													if( !empty( $updatedData ) ){
														$updateRowEmail .= ' '.sprintf( __('Updated Data: %s, %s', CIP_TXTDOMAIN), 'Ref('.$getRecordByusername->reference.')', implode(', ', $updatedData) );
													}else{
														$updateRowEmail .= 'Ref('.$getRecordByusername->reference.')';
													}
												}
												$userData = wp_get_current_user();
												$user_roles = $userData->roles;
												$user_role = array_shift($user_roles);
												$logs = sprintf( __('%s (%s) %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $updateRowEmail );
												create_cip_logs_entery( $user->ID, 'update_holder_bulk', '','sa', $logs, true );
											}
										}
									}
									if( $updateingToggleValue === true ){
										$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
										if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
											update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
										}
									}

									/* $where = [ 'username' => $_POST['username'] ];
									$data['last_update'] = date_i18n('Y-m-d H:i:s');
									$updating = $wpdb->update( $tableName, $data, $where );

									if( $updating ){
										$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
										$updateRowEmail = "";
										$updateRowEmail = "update holder by username(".$_POST['username'].")";
										$log_type = 'update_holder';
										$user = wp_get_current_user();
										create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail );
										if( $getUpdateEmailData ){
											if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
												update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
											}
										}
									}else{
										$out = array( "error" => 1,'msg' => $wpdb->last_error );
									} */
								}
							}else{
								$out = array( "error" => 1,'msg' => __('Update failed : by username update, main username is change',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							if( $checkUsername->username ){
								$getUpdateEmailData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id`=".$_POST['sathid']."");
								$getRecordsByusername = $wpdb->get_results("SELECT * FROM $tableName WHERE `username`='". $checkUsername->username ."'");
								if( $getRecordsByusername ){
									foreach( $getRecordsByusername as $getRecordByusername ){
										$where = [ 'id' => $getRecordByusername->id ];
										$data['last_update'] = date_i18n('Y-m-d H:i:s');

										//exclude Issued and Delivered status to update when change status to hold or security hold
										$holdStatusArray = array( 'Hold', 'Security Hold' );
										$issuedStatusArray = array( 'Issued', 'Delivered' );
										if( isset( $_POST['corp_approved'] ) && in_array( $_POST['corp_approved'], $holdStatusArray ) ){ //check is hold or security hold status
											if( in_array(  $getRecordByusername->corp_approved, $issuedStatusArray ) ){	//check already have issued or delivered status
												$updatingData = $data;
												unset( $updatingData['corp_approved'] );
											}else{
												$updatingData = $data;
											}
										}else{
											$updatingData = $data;
										}

										$updating = $wpdb->update( $tableName, $updatingData, $where );
										if( $updating ){
											$updateingToggleValue = true;
											$updateRowEmail = "";
											$updatedData = array();
											if( $getRecordByusername ){
												$updateRowEmail = "updated holder by username(".$checkUsername->username.") at ".date_i18n('d/m/Y H:i A').". ";
												foreach( $updatingData as $columnKey => $columnLbl ){
													if( isset( $_POST[ $columnKey ] ) ){
														if( $getRecordByusername->$columnKey != $_POST[ $columnKey ] ){
															$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getRecordByusername->$columnKey, $_POST[ $columnKey ] );
														}
													}
												}
												if( !empty( $updatedData ) ){
													$updateRowEmail .= ' '.sprintf( __('Updated Data: %s, %s', CIP_TXTDOMAIN), 'Ref('.$getRecordByusername->reference.')', implode(', ', $updatedData) );
												}else{
													$updateRowEmail .= 'Ref('.$getRecordByusername->reference.')';
												}
											}
											$userData = wp_get_current_user();
											$user_roles = $userData->roles;
											$user_role = array_shift($user_roles);
											$logs = sprintf( __('%s (%s) %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $updateRowEmail );
											create_cip_logs_entery( $user->ID, 'update_holder_bulk', '','sa', $logs, true );
										}
									}
								}
								if( $updateingToggleValue === true ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
									if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
										update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
									}
								}

								/* $where = [ 'username' => $checkUsername->username ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');
								$updating = $wpdb->update( $tableName, $data, $where );

								if( $updating ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
									$updateRowEmail = "";
									$updateRowEmail = "update holder by username(".$checkUsername->username.")";
									$log_type = 'update_holder';
									$user = wp_get_current_user();
									create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail );
									if( $getUpdateEmailData ){
										if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
											update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
										}
									}
								}else{
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								} */
							}else{
								$out = array( "error" => 1,'msg' => __('Update failed : username not found',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}
					}else if( $_POST['update_all_option'] == 'all_email_update' ){ //by email update
						$checkEmail = $wpdb->get_row("SELECT email FROM $tableName WHERE id = ".$_POST['sathid']."");
						if( $checkEmail->email == $_POST['email'] ){
							if( isset( $_POST['email'] ) && !empty( $_POST['email'] ) ){
								$getRecordsByemail = $wpdb->get_results("SELECT * FROM $tableName WHERE `email`='". $_POST['email'] ."'");
								if( $getRecordsByemail ){
									foreach( $getRecordsByemail as $getRecordByemail ){
										$where = [ 'id' => $getRecordByemail->id ];
										$data['last_update'] = date_i18n('Y-m-d H:i:s');

										//exclude Issued and Delivered status to update when change status to hold or security hold
										$holdStatusArray = array( 'Hold', 'Security Hold' );
										$issuedStatusArray = array( 'Issued', 'Delivered' );
										if( isset( $_POST['corp_approved'] ) && in_array( $_POST['corp_approved'], $holdStatusArray ) ){ //check is hold or security hold status
											if( in_array(  $getRecordByemail->corp_approved, $issuedStatusArray ) ){	//check already have issued or delivered status
												$updatingData = $data;
												unset( $updatingData['corp_approved'] );
											}else{
												$updatingData = $data;
											}
										}else{
											$updatingData = $data;
										}

										$updating = $wpdb->update( $tableName, $updatingData, $where );
										if( $updating ){
											$updateingToggleValue = true;
											$updateRowEmail = "";
											$updatedData = array();
											if( $getRecordByemail ){
												$updateRowEmail = "updated holder by email(".$_POST['email'].") at ".date_i18n('d/m/Y H:i A').". ";
												foreach( $updatingData as $columnKey => $columnLbl ){
													if( isset( $_POST[ $columnKey ] ) ){
														if( $getRecordByemail->$columnKey != $_POST[ $columnKey ] ){
															$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getRecordByemail->$columnKey, $_POST[ $columnKey ] );
														}
													}
												}
												if( !empty( $updatedData ) ){
													$updateRowEmail .= ' '.sprintf( __('Updated Data:  %s, %s', CIP_TXTDOMAIN), 'Ref('.$getRecordByemail->reference.')', implode(', ', $updatedData) );
												}else{
													$updateRowEmail .= 'Ref('.$getRecordByemail->reference.')';
												}
											}
											$userData = wp_get_current_user();
											$user_roles = $userData->roles;
											$user_role = array_shift($user_roles);
											$logs = sprintf( __('%s (%s) %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $updateRowEmail );
											create_cip_logs_entery( $user->ID, 'update_holder_bulk', '','sa', $logs, true );
										}
									}
								}
								if( $updateingToggleValue === true ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
								}
								/* $where = [ 'email' => $_POST['email'] ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');
								$updating = $wpdb->update( $tableName, $data, $where );
								if( $updating ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
									$updateRowEmail = "";
									$updateRowEmail = "update holder by email(".$_POST['email'].")";
									$log_type = 'update_holder';
									$user = wp_get_current_user();
									create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail );
								}else{
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								} */
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : by email update, main email is change',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else if( $_POST['update_all_option'] == 'all_wallet_address_update' ){ //by wallet address update
						$checkWallertAddress = $wpdb->get_row("SELECT eth_address FROM $tableName WHERE id = ".$_POST['sathid']."");
						if( $checkWallertAddress->eth_address == $_POST['eth_address'] ){
							if( ( isset( $_POST['eth_address'] ) && empty( $_POST['eth_address'] ) ) || empty( $checkWallertAddress->eth_address ) ){
								$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, address is empty',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
							if( isset( $_POST['eth_address'] ) && !empty( $_POST['eth_address'] ) ){
								$getUpdateEmailData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id`=".$_POST['sathid']."");
								$getRecordsByaddress = $wpdb->get_results("SELECT * FROM $tableName WHERE `eth_address`='". $_POST['eth_address'] ."'");
								if( $getRecordsByaddress ){
									foreach( $getRecordsByaddress as $getRecordByaddress ){
										$where = [ 'id' => $getRecordByaddress->id ];
										$data['last_update'] = date_i18n('Y-m-d H:i:s');

										//exclude Issued and Delivered status to update when change status to hold or security hold
										$holdStatusArray = array( 'Hold', 'Security Hold' );
										$issuedStatusArray = array( 'Issued', 'Delivered' );
										if( isset( $_POST['corp_approved'] ) && in_array( $_POST['corp_approved'], $holdStatusArray ) ){ //check is hold or security hold status
											if( in_array(  $getRecordByaddress->corp_approved, $issuedStatusArray ) ){	//check already have issued or delivered status
												$updatingData = $data;
												unset( $updatingData['corp_approved'] );
											}else{
												$updatingData = $data;
											}
										}else{
											$updatingData = $data;
										}

										$updating = $wpdb->update( $tableName, $updatingData, $where );
										if( $updating ){
											$updateingToggleValue = true;
											$updateRowEmail = "";
											$updatedData = array();
											if( $getRecordByaddress ){
												$updateRowEmail = "updated holder by eth_address(".$_POST['eth_address'].") at ".date_i18n('d/m/Y H:i A').". ";
												foreach( $updatingData as $columnKey => $columnLbl ){
													if( isset( $_POST[ $columnKey ] ) ){
														if( $getRecordByaddress->$columnKey != $_POST[ $columnKey ] ){
															$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getRecordByaddress->$columnKey, $_POST[ $columnKey ] );
														}
													}
												}
												if( !empty( $updatedData ) ){
													$updateRowEmail .= ' '.sprintf( __('Updated Data: %s, %s', CIP_TXTDOMAIN), 'Ref('.$getRecordByaddress->reference.')', implode(', ', $updatedData) );
												}else{
													$updateRowEmail .= 'Ref('.$getRecordByaddress->reference.')';
												}
											}
											$userData = wp_get_current_user();
											$user_roles = $userData->roles;
											$user_role = array_shift($user_roles);
											$logs = sprintf( __('%s (%s) %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $updateRowEmail );
											create_cip_logs_entery( $user->ID, 'update_holder_bulk', '','sa', $logs, true );
										}
									}
								}
								if( $updateingToggleValue === true ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
									if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
										update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
									}
								}

								/* $where = [ 'eth_address' => $_POST['eth_address'] ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');
								$updating = $wpdb->update( $tableName, $data, $where );

								if( $updating ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
									$updateRowEmail = "";
									$updateRowEmail = "update holder by eth_address(".$_POST['eth_address'].")";
									$log_type = 'update_holder';
									$user = wp_get_current_user();
									create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail );
									if( $getUpdateEmailData ){
										if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
											update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
										}
									}
								}else{
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								} */
							}else{
								$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, address is empty',CIP_TXTDOMAIN) );
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, main wallet address is change',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else if( $_POST['update_all_option'] == 'all_reference_update' ){ //by reference update

						$reference_like = $_POST['reference_update_field'];
						$getReferences = $wpdb->get_results("SELECT * FROM $tableName WHERE reference LIKE '".$reference_like."%'");
						if( $getReferences ){
							$byRefUpdate = false;

							$getUpdateEmailData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id`=".$_POST['sathid']."");

							foreach( $getReferences as $singleRef ){
								$where = [ 'id' => $singleRef->id ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');

								//exclude Issued and Delivered status to update when change status to hold or security hold
								$holdStatusArray = array( 'Hold', 'Security Hold' );
								$issuedStatusArray = array( 'Issued', 'Delivered' );
								if( isset( $_POST['corp_approved'] ) && in_array( $_POST['corp_approved'], $holdStatusArray ) ){ //check is hold or security hold status
									if( in_array(  $singleRef->corp_approved, $issuedStatusArray ) ){	//check already have issued or delivered status
										$updatingData = $data;
										unset( $updatingData['corp_approved'] );
									}else{
										$updatingData = $data;
									}
								}else{
									$updatingData = $data;
								}

								$updating = $wpdb->update( $tableName, $updatingData, $where );
								if( $updating ){
									$byRefUpdate = true;
									$updateRowEmail = "";
									$updatedData = array();
									if( $singleRef ){
										$updateRowEmail = "updated holder by reference(".$reference_like.") at ".date_i18n('d/m/Y H:i A').". ";
										foreach( $updatingData as $columnKey => $columnLbl ){
											if( isset( $_POST[ $columnKey ] ) ){
												if( $singleRef->$columnKey != $_POST[ $columnKey ] ){
													$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $singleRef->$columnKey, $_POST[ $columnKey ] );
												}
											}
										}
										if( !empty( $updatedData ) ){
											$updateRowEmail .= ' '.sprintf( __('Updated Data: %s, %s', CIP_TXTDOMAIN), 'Ref('.$singleRef->reference.')', implode(', ', $updatedData) );
										}else{
											$updateRowEmail .= 'Ref('.$singleRef->reference.')';
										}
									}
									$userData = wp_get_current_user();
									$user_roles = $userData->roles;
									$user_role = array_shift($user_roles);
									$logs = sprintf( __('%s (%s) %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $updateRowEmail );
									create_cip_logs_entery( $user->ID, 'update_holder_bulk', '','sa', $logs, true );
								}
							}
							if( $byRefUpdate ){
								$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
								/* $updateRowEmail = "";
								$updateRowEmail = "update holder by reference(".$reference_like.")";
								$log_type = 'update_holder';
								$user = wp_get_current_user();
								create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail ); */
								if( $getUpdateEmailData ){
									if( isset( $_POST['email'] ) && ( $getUpdateEmailData->email != $_POST['email'] ) && ( !empty( $getUpdateEmailData->email ) && !empty( $_POST['email'] ) ) ){
										update_email_to_related_tables( $getUpdateEmailData->email, $_POST['email'] );
									}
								}
							}else{
								$out = array( "error" => 1,'msg' => $wpdb->last_error );
							}
						}else{
							$out = array( "error" => 1,'msg' => __('No result found for given matching reference',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

					}else{
						$out = array( "error" => 1,'msg' => __('Update all option not found from list',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}else{
				$data = array();
				$validationError = [];
				$rowError = false;
				foreach( $defaultColumnsArr as $columnKey => $columnLbl ){

					if( $columnKey == 'email' && isset( $_POST[ $columnKey ] ) && !filter_var($_POST[ $columnKey ], FILTER_VALIDATE_EMAIL) ){
						$rowError = true;
						$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'occurs_times' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'csramount_by_ethaddress' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'csr_amount_initial' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'amount_due' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'csramount_byusername' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'csr_amount_issued' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'occurs_times_user' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'redemption_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
						$rowError = true;
						$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'claim_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
						$rowError = true;
						$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
					}
					if( $columnKey == 'position' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
						$rowError = true;
						$validationError[] = __('Position is not numeric',CIP_TXTDOMAIN);
					}
					if( isset( $_POST[ $columnKey ] ) ){
						$data[ $columnKey ] = wp_unslash( $_POST[ $columnKey ] );
					}
				}

				if( $rowError === true ){
					$out = array( "error" => 1,'msg' => implode(', ', $validationError) );
					echo wp_json_encode( $out );
					exit;
				}
				if( ( isset($_POST['username'] ) && $_POST['username'] != "" ) && ( isset($_POST['email'] ) && $_POST['email'] != "" ) ){
					$check_duplicate_email = $wpdb->get_results("SELECT * FROM $tableName WHERE email = '".$_POST['email']."' AND username != '".$_POST['username']."' ");
					if( $check_duplicate_email ){
						$out = array( "error" => 1,'msg' => __('The email have already assigned other username') );
						echo wp_json_encode( $out );
						exit;
					}
				}
				/*if( isset( $_POST['first_name'] ) && isset( $_POST['email'] ) ){
					$dataFName = array( 'first_name' => $_POST['first_name'] );
					$whereFName = [ 'email' => $_POST['email'] ];
					$updateFName = $wpdb->update( $tableName, $dataFName, $whereFName );
				}
				if( isset( $_POST['last_name'] ) && isset( $_POST['email'] ) ){
					$dataLName = array( 'last_name' => $_POST['last_name'] );
					$whereLName = [ 'email' => $_POST['email'] ];
					$updateLName = $wpdb->update( $tableName, $dataLName, $whereLName );
				}*/

				$updateRowEmail = "";
				$updatedData = array();
				$getUpdateEmailData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id`=".$_POST['sathid']."");
				if( $getUpdateEmailData ){
					$updateRowEmail = "holder email(".$getUpdateEmailData->email.")";
					foreach( $defaultColumnsArr as $columnKey => $columnLbl ){
						if( isset( $_POST[ $columnKey ] ) ){
							if( $getUpdateEmailData->$columnKey != $_POST[ $columnKey ] ){
								$updatedData[] = sprintf( __('%s => %s to %s', CIP_TXTDOMAIN), $columnKey, $getUpdateEmailData->$columnKey, $_POST[ $columnKey ] );
							}
						}
					}
					if( !empty( $updatedData ) ){
						$updateRowEmail .= ' '.sprintf( __('Updated Data: %s', CIP_TXTDOMAIN), implode(', ', $updatedData) );
					}
				}
				$where = [ 'id' => $_POST['sathid'] ];
				$data['last_update'] = date_i18n('Y-m-d H:i:s');
				$updating = $wpdb->update( $tableName, $data, $where );
				if( $updating ){
					$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
				}else{
					$out = array( "error" => 1,'msg' => $wpdb->last_error );
				}
				$log_type = 'update_holder';
				$user = wp_get_current_user();
				create_cip_logs_entery( $user->ID, $log_type , $updateRowEmail );
				if( get_sms_send_toggle('csr_holder_update') == 1 ){
					$content = sprintf(__('CSR holder table record with reference changed by %s. %s', CIP_TXTDOMAIN), $current_user->user_email, $updateRowEmail );
					brevo_sms_alert_send( $content );
				}
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function update_email_to_related_tables( $oldEmail = "", $newEmail = "" ){
	global $wpdb;
	$current_user = wp_get_current_user();
	$table_cip_member_invoice = $wpdb->prefix.'cip_member_invoice';
	$table_cip_notice = $wpdb->prefix.'cip_notice';
	$table_csr_address_pending = $wpdb->prefix.'csr_address_pending';
	$table_csr_delivery_transaction_history = $wpdb->prefix.'csr_delivery_transaction_history';
	$table_csr_lsh_pending = $wpdb->prefix.'csr_lsh_pending';
	$table_kyc_data = $wpdb->prefix.'kyc_data';
	$table_retirement_data = $wpdb->prefix.'retirement_data';
	$table_retirement_setting = $wpdb->prefix.'retirement_setting';
	$table_weekly_distribution_export = $wpdb->prefix.'weekly_distribution_export';
	$table_withdraw_data_completed = $wpdb->prefix.'withdraw_data_completed';
	$table_withdraw_data_pending = $wpdb->prefix.'withdraw_data_pending';

	$table_token_holder_distribution = $wpdb->prefix.'token_holder_distribution';
	$table_token_holder_distribution_temp = $wpdb->prefix.'token_holder_distribution_temp';
	$table_withdraw_data_inprocess = $wpdb->prefix.'withdraw_data_inprocess';

	$table_csr_savings = $wpdb->prefix.'csr_savings';
	$table_internaltransfer = $wpdb->prefix.'internaltransfer';

	if( !empty( $oldEmail ) && !empty( $newEmail ) ){

		$table_cip_member_invoice_update_row = $wpdb->update( $table_cip_member_invoice, [ 'Email' => $newEmail ], [ 'Email' => $oldEmail ] );
		if( $table_cip_member_invoice_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_cip_member_invoice, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_cip_notice_update_row = $wpdb->update( $table_cip_notice, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_cip_notice_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_cip_notice, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_csr_address_pending_update_row = $wpdb->update( $table_csr_address_pending, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_csr_address_pending_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_csr_address_pending, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_csr_delivery_transaction_history_update_row = $wpdb->update( $table_csr_delivery_transaction_history, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_csr_delivery_transaction_history_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_csr_delivery_transaction_history, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_csr_lsh_pending_update_row = $wpdb->update( $table_csr_lsh_pending, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_csr_lsh_pending_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_csr_lsh_pending, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_kyc_data_update_row = $wpdb->update( $table_kyc_data, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_kyc_data_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_kyc_data, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_retirement_data_update_row = $wpdb->update( $table_retirement_data, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_retirement_data_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_retirement_data, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_retirement_setting_update_row = $wpdb->update( $table_retirement_setting, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_retirement_setting_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_retirement_setting, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_weekly_distribution_export_update_row = $wpdb->update( $table_weekly_distribution_export, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_weekly_distribution_export_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_weekly_distribution_export, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_withdraw_data_completed_update_row = $wpdb->update( $table_withdraw_data_completed, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_withdraw_data_completed_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_withdraw_data_completed, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_withdraw_data_pending_update_row = $wpdb->update( $table_withdraw_data_pending, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_withdraw_data_pending_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_withdraw_data_pending, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_token_holder_distribution_update_row = $wpdb->update( $table_token_holder_distribution, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_token_holder_distribution_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_token_holder_distribution, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_token_holder_distribution_temp_update_row = $wpdb->update( $table_token_holder_distribution_temp, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_token_holder_distribution_temp_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_token_holder_distribution_temp, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_withdraw_data_inprocess_update_row = $wpdb->update( $table_withdraw_data_inprocess, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_withdraw_data_inprocess_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_withdraw_data_inprocess, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_csr_savings_update_row = $wpdb->update( $table_csr_savings, [ 'email' => $newEmail ], [ 'email' => $oldEmail ] );
		if( $table_csr_savings_update_row ){
			$logs = sprintf( __('Bulk email update from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_csr_savings, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_internaltransfer_update_row = $wpdb->update( $table_internaltransfer, [ 'from_user' => $newEmail ], [ 'from_user' => $oldEmail ] );
		if( $table_internaltransfer_update_row ){
			$logs = sprintf( __('Bulk email update from_user from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_internaltransfer, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		$table_internaltransfer_update_row = $wpdb->update( $table_internaltransfer, [ 'to_user' => $newEmail ], [ 'to_user' => $oldEmail ] );
		if( $table_internaltransfer_update_row ){
			$logs = sprintf( __('Bulk email update to_user from %s to %s to table %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $table_internaltransfer, $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		}

		//updating wordpress user email address
		$oldUserData = get_user_by( 'email', $oldEmail );
		if( $oldUserData && $oldUserData->ID ){
			if( !email_exists( $newEmail ) ){
				$argsEmailUpdate = array(
					'ID'         => $oldUserData->ID,
					'user_email' => esc_attr( $newEmail )
				);
				$newUpdateEmailData = wp_update_user( $argsEmailUpdate );
				if( !is_wp_error( $newUpdateEmailData ) ) {
					$logs = sprintf( __('WP user email update from %s to %s. by %s at %s', CIP_TXTDOMAIN), $oldEmail, $newEmail, $current_user->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
				}
			}
		}

	}
}
//MA enabled update code
add_action('wp_ajax_ma_update_th_tp1_act','ma_update_th_tp1_act_cb');
function ma_update_th_tp1_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XMAupdatethtp1MAX_' ) ){
		global $wpdb;
		global $defaultColumnsArr;
		$tableName = $wpdb->prefix.'token_holder';
		if( isset( $_POST['update_all_match'] ) && $_POST['update_all_match'] == 1 && $_POST['update_all_option'] != 'single_row_update' ){ //condition based update

			if( $_POST['update_all_option'] == 'all_username_update' || $_POST['update_all_option'] == 'all_email_update' || $_POST['update_all_option'] == 'all_reference_update' || $_POST['update_all_option'] == 'all_wallet_address_update' ){
				$data = array();
				$validationError = [];
				$rowError = false;
				if( $_POST['update_all_option'] == 'all_username_update' ){
					unset( $defaultColumnsArr['username'] );
				}else if( $_POST['update_all_option'] == 'all_email_update' ){
					unset( $defaultColumnsArr['email'] );
				}else if( $_POST['update_all_option'] == 'all_reference_update' ){
					unset( $defaultColumnsArr['reference'] );
				}else if( $_POST['update_all_option'] == 'all_wallet_address_update' ){
					unset( $defaultColumnsArr['eth_address'] );
				}
				$checkOgData = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['sathid']."  AND ma_enabled = 1");
				foreach( $defaultColumnsArr as $columnKey => $columnLbl ){

					if( $columnKey == 'first_name' || $columnKey == 'last_name' || $columnKey == 'email' || $columnKey == 'eth_address' ){
						if( $columnKey == 'eth_address' && !empty( $checkOgData->$columnKey ) ){
							continue;
						}
					}else{
						continue;
					}

					if( $checkOgData->$columnKey != $_POST[ $columnKey ] && ( !empty( $checkOgData->$columnKey ) || !empty( $_POST[ $columnKey ] ) ) ){
						//continue for update
					}else{
						//continue for skip
						continue;
					}
					if( $columnKey == 'email' && isset( $_POST[ $columnKey ] ) && !filter_var($_POST[ $columnKey ], FILTER_VALIDATE_EMAIL) ){
						$rowError = true;
						$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
					}
					if( isset( $_POST[ $columnKey ] ) ){
						$data[ $columnKey ] = wp_unslash( $_POST[ $columnKey ] );
					}
				}

				if( $rowError === true ){
					$out = array( "error" => 1,'msg' => implode(', ', $validationError) );
					echo wp_json_encode( $out );
					exit;
				}
				if( $_POST['update_all_option'] == 'all_username_update' ){ //by username update
					$checkUsername = $wpdb->get_row("SELECT username FROM $tableName WHERE id = ".$_POST['sathid']." AND ma_enabled = 1");
					if( isset( $_POST['username'] ) ){
						if( $checkUsername->username == $_POST['username'] ){
							if( isset( $_POST['username'] ) && !empty( $_POST['username'] ) ){
								$where = [ 'username' => $_POST['username'], 'ma_enabled' => 1 ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');
								$updating = $wpdb->update( $tableName, $data, $where );
								if( $updating ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
								}else{
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								}
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : by username update, main username is change',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else{
						if( $checkUsername->username ){
							$where = [ 'username' => $checkUsername->username, 'ma_enabled' => 1  ];
							$data['last_update'] = date_i18n('Y-m-d H:i:s');
							$updating = $wpdb->update( $tableName, $data, $where );
							if( $updating ){
								$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
							}else{
								$out = array( "error" => 1,'msg' => $wpdb->last_error );
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : username not found',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}else if( $_POST['update_all_option'] == 'all_email_update' ){ //by email update
					$checkEmail = $wpdb->get_row("SELECT email FROM $tableName WHERE id = ".$_POST['sathid']."  AND ma_enabled = 1");
					if( $checkEmail->email == $_POST['email'] ){
						if( isset( $_POST['email'] ) && !empty( $_POST['email'] ) ){
							$where = [ 'email' => $_POST['email'], 'ma_enabled' => 1  ];
							$data['last_update'] = date_i18n('Y-m-d H:i:s');
							$updating = $wpdb->update( $tableName, $data, $where );
							if( $updating ){
								$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
							}else{
								$out = array( "error" => 1,'msg' => $wpdb->last_error );
							}
						}
					}else{
						$out = array( "error" => 1,'msg' => __('Update failed : by email update, main email is change',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}else if( $_POST['update_all_option'] == 'all_wallet_address_update' ){ //by wallet address update
					$checkWallertAddress = $wpdb->get_row("SELECT eth_address FROM $tableName WHERE id = ".$_POST['sathid']." AND ma_enabled = 1");
					if( isset( $_POST['eth_address'] ) ){
						if( $checkWallertAddress->eth_address == $_POST['eth_address'] ){

							if( ( isset( $_POST['eth_address'] ) && empty( $_POST['eth_address'] ) ) || empty( $checkWallertAddress->eth_address ) ){
								$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, address is empty',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}

							if( isset( $_POST['eth_address'] ) && !empty( $_POST['eth_address'] ) ){
								$where = [ 'eth_address' => $_POST['eth_address'], 'ma_enabled' => 1  ];
								$data['last_update'] = date_i18n('Y-m-d H:i:s');
								$updating = $wpdb->update( $tableName, $data, $where );
								if( $updating ){
									$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
								}else{
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								}
							}else{
								$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, address is empty',CIP_TXTDOMAIN) );
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, main wallet address is change',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else{

						if( $checkWallertAddress->eth_address ){

							$where = [ 'eth_address' => $checkWallertAddress->eth_address, 'ma_enabled' => 1  ];
							$data['last_update'] = date_i18n('Y-m-d H:i:s');
							$updating = $wpdb->update( $tableName, $data, $where );
							if( $updating ){
								$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
							}else{
								$out = array( "error" => 1,'msg' => $wpdb->last_error );
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Update failed : by wallet address update, address is empty',CIP_TXTDOMAIN) );
						}
					}
				}else if( $_POST['update_all_option'] == 'all_reference_update' ){ //by reference update

					$reference_like = $_POST['reference_update_field'];
					$getReferences = $wpdb->get_results("SELECT id FROM $tableName WHERE reference LIKE '".$reference_like."%'  AND ma_enabled = 1");
					if( $getReferences ){
						$byRefUpdate = false;
						foreach( $getReferences as $singleRef ){
							$where = [ 'id' => $singleRef->id, 'ma_enabled' => 1  ];
							$data['last_update'] = date_i18n('Y-m-d H:i:s');
							$updating = $wpdb->update( $tableName, $data, $where );
							if( $updating ){ $byRefUpdate = true; }
						}
						if( $byRefUpdate ){
							$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
						}else{
							$out = array( "error" => 1,'msg' => $wpdb->last_error );
						}
					}else{
						$out = array( "error" => 1,'msg' => __('No result found for given matching reference',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}

				}else{
					$out = array( "error" => 1,'msg' => __('Update all option not found from list',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
		}else{
			$data = array();
			$validationError = [];
			$rowError = false;
			$checkOgData = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['sathid']." AND ma_enabled = 1");
			foreach( $defaultColumnsArr as $columnKey => $columnLbl ){
				if( $columnKey == 'first_name' || $columnKey == 'last_name' || $columnKey == 'email' || $columnKey == 'eth_address' ){
					if( $columnKey == 'eth_address' && !empty( $checkOgData->$columnKey ) ){
						continue;
					}
				}else{
					continue;
				}

				if( $columnKey == 'email' && isset( $_POST[ $columnKey ] ) && !filter_var($_POST[ $columnKey ], FILTER_VALIDATE_EMAIL) ){
					$rowError = true;
					$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'occurs_times' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'csramount_by_ethaddress' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'csr_amount_initial' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'amount_due' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'csramount_byusername' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'csr_amount_issued' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'occurs_times_user' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'redemption_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
					$rowError = true;
					$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'claim_date' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && DateTime::createFromFormat('d/n/Y', $_POST[ $columnKey ]) === false ){
					$rowError = true;
					$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
				}
				if( $columnKey == 'position' && isset( $_POST[ $columnKey ] ) && !empty( $_POST[ $columnKey ] ) && !is_numeric( $_POST[ $columnKey ] ) ){
					$rowError = true;
					$validationError[] = __('Position is not numeric',CIP_TXTDOMAIN);
				}
				if( isset( $_POST[ $columnKey ] ) ){
					$data[ $columnKey ] = wp_unslash( $_POST[ $columnKey ] );
				}
			}
			if( $rowError === true ){
				$out = array( "error" => 1,'msg' => implode(', ', $validationError) );
				echo wp_json_encode( $out );
				exit;
			}
			$where = [ 'id' => $_POST['sathid'], 'ma_enabled' => 1  ];
			$data['last_update'] = date_i18n('Y-m-d H:i:s');
			$updating = $wpdb->update( $tableName, $data, $where );
			if( $updating ){
				$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => $wpdb->last_error );
			}
			$updateRowEmail = "";
			$updatedData = array();
			$getUpdateEmailData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id`=".$_POST['sathid']."");
			if( $getUpdateEmailData ){
				$updateRowEmail = "holder email(".$getUpdateEmailData->email.")";
				foreach( $defaultColumnsArr as $columnKey => $columnLbl ){
					if( isset( $_POST[ $columnKey ] ) ){
						if( $getUpdateEmailData->$columnKey != $_POST[ $columnKey ] ){
							$updatedData[] = sprintf( __('%s => %s to %s', CIP_TXTDOMAIN), $columnKey, $getUpdateEmailData->$columnKey, $_POST[ $columnKey ] );
						}
					}
				}
				if( !empty( $updatedData ) ){
					$updateRowEmail .= ' '.sprintf( __('Updated Data: %s', CIP_TXTDOMAIN), implode(', ', $updatedData) );
				}
			}
			$log_type = 'update_holder';
			$user = wp_get_current_user();
			create_cip_logs_entery( $user->ID, $log_type, $updateRowEmail );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sa_delth_act','sa_delth_act_cb');
function sa_delth_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	//if( wp_verify_nonce( $_POST['_micro'],'_Xupdatethtp1X_' ) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		$user_id = get_current_user_id();
		$getSingleTh = $wpdb->get_row("SELECT id FROM $tableName WHERE id = ".$_POST['sathid']."");
		if( $getSingleTh ){
			$where = [ 'id' => $_POST['sathid'] ];
			$deleting = $wpdb->delete( $tableName, $where );
			$out = array( "error" => 0,'msg' => __('Record Deleted',CIP_TXTDOMAIN) );
			$log_type = 'delete_holder';
			$user = wp_get_current_user();
			create_cip_logs_entery( $user->ID, $log_type );
		}else{
			$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
		}
	// }
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sasm_updatestatus_act','sasm_updatestatus_act_cb');
function sasm_updatestatus_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$update = update_user_meta( $_POST['cipthisid'], 'cip_user_status', $_POST['cipthisval'] );
	if( $update ){
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sasm_update_profile_act','sasm_update_profile_act_cb');
function sasm_update_profile_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XupdatesasmprofX_' ) ){
		update_user_meta( $_POST['sasmuid'], 'first_name', $_POST['firstname'] );
		update_user_meta( $_POST['sasmuid'], 'last_name', $_POST['lastname'] );
		update_user_meta( $_POST['sasmuid'], 'phonenumber', $_POST['phonenumber'] );
		update_user_meta( $_POST['sasmuid'], 'cip_user_status', $_POST['user_status'] );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
		$log_type = 'update_profile';
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_own_update_profile_act','own_update_profile_act_cb');
function own_update_profile_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XupdateownprofX_' ) ){
		$currentUser = wp_get_current_user();
		update_user_meta( $currentUser->ID, 'first_name', $_POST['firstname'] );
		update_user_meta( $currentUser->ID, 'last_name', $_POST['lastname'] );
		update_user_meta( $currentUser->ID, 'phonenumber', $_POST['phonenumber'] );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
		$log_type = 'update_profile';
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_columnorderupdate_act','sm_update_column_order_cb');
function sm_update_column_order_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyUpdateColumnOrderyX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$column_order_arr = array();
		foreach ($_POST['column_order'] as &$column_order_val){
		   $column_order_arr[] = strtolower(str_replace('.', '_', $column_order_val));
		}
		update_option( 'cip_sm_column_order', $column_order_arr );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sm_column_manage_act','sm_column_manage_act_cb');
function sm_column_manage_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $defaultColumnsArr;
	if( wp_verify_nonce( $_POST['_micro'],'_XsmcolumnmanageX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$column_label_arr = array();
		if( !empty( $_POST['column_label'] ) ){
			foreach ($_POST['column_label'] as $column_labelKey => &$column_labelVal ){
			   $column_label_arr[$column_labelKey] = esc_html( $column_labelVal );
			}
		}
		update_option( 'cip_sm_column_labels', $column_label_arr );
		$args = array( 'role__in'  =>	array('supportagent') );
		$saUsers = get_users( $args );
		$saNewUpdateColArr = array();
		foreach( $saUsers as $saUser ){
			$user_id = $saUser->ID;
			$saSavedColumn = (array)get_user_meta( $user_id, 'cip_sagent_toggle_columns', true );
			foreach( $defaultColumnsArr as $defaultColumnKey => $defaultColumnVal ){
				if( isset( $_POST['column_sa_toggle'][ $defaultColumnKey ] ) ){
				}else{
					unset( $saSavedColumn[ $defaultColumnKey ] );
				}
				/*foreach( $_POST['column_sa_toggle'] as $columnSAToggleKey => &$columnSAToggleVal ){
					if( !isset( $saSavedColumn[ $defaultColumnKey ] ) ){
						unset( $saSavedColumn[ $columnSAToggleKey ] );
					}
				}*/
			}
			update_user_meta( $user_id, 'cip_sagent_toggle_columns', $saSavedColumn );
		}
		$column_sa_toggle_arr = array();
		if( !empty( $_POST['column_sa_toggle'] ) ){
			foreach ($_POST['column_sa_toggle'] as $columnSAToggleKey => &$columnSAToggleVal ){
			   $column_sa_toggle_arr[$columnSAToggleKey] = ( isset( $columnSAToggleVal ) && $columnSAToggleVal == 1 ) ? 1 : 0;
			}
		}
		update_option( 'cip_column_sa_toggle_columns', $column_sa_toggle_arr );
		$column_th_toggle_arr = array();
		if( !empty( $_POST['column_th_toggle'] ) ){
			foreach ($_POST['column_th_toggle'] as $columnTHToggleKey => &$columnTHToggleVal ){
			   $column_th_toggle_arr[$columnTHToggleKey] = ( isset( $columnTHToggleVal ) && $columnTHToggleVal == 1 ) ? 1 : 0;
			}
		}
		update_option( 'cip_column_th_toggle_columns', $column_th_toggle_arr );
		/*$column_saedit_toggle_arr = array();
		if( !empty( $_POST['column_saedt_toggle'] ) ){
			foreach ($_POST['column_saedt_toggle'] as $columnSAEditToggleKey => &$columnSAEditToggleVal ){
			   $column_saedit_toggle_arr[$columnSAEditToggleKey] = ( isset( $columnSAEditToggleVal ) && $columnSAEditToggleVal == 1 ) ? 1 : 0;
			}
		}
		update_option( 'cip_column_saedit_toggle_columns', $column_saedit_toggle_arr );*/
		$log_type = 'column_update';
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sa_column_manage_act','sa_column_manage_act_cb');
function sa_column_manage_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XsacolumnmanageX_' ) && current_user_can( 'supportagent' ) ){
		$user_id = get_current_user_id();
		$column_sa_toggle_arr = array();
		if( !empty( $_POST['column_sa_toggle'] ) ){
			foreach ($_POST['column_sa_toggle'] as $columnSAToggleKey => &$columnSAToggleVal ){
			   $column_sa_toggle_arr[$columnSAToggleKey] = ( isset( $columnSAToggleVal ) && $columnSAToggleVal == 1 ) ? 1 : 0;
			}
		}
		update_user_meta( $user_id, 'cip_sagent_toggle_columns', $column_sa_toggle_arr );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
		$log_type = 'column_update';
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_th_column_manage_act','th_column_manage_act_cb');
function th_column_manage_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$tableNameCol = $wpdb->prefix.'token_holder_columns';
	$refAccount = $_SESSION['refAccount'];
	$getCurrentMembers = $wpdb->get_row("SELECT id FROM $tableName WHERE email = '".$refAccount."' ");
	if( wp_verify_nonce( $_POST['_micro'],'_XthcolumnmanageX_' ) && $getCurrentMembers ){
		$getMembersColumns = $wpdb->get_row("SELECT * FROM $tableNameCol WHERE email = '".$refAccount."' ");
		$column_th_toggle_arr = array();
		if( !empty( $_POST['column_th_toggle'] ) ){
			foreach ($_POST['column_th_toggle'] as $columnTHToggleKey => &$columnTHToggleVal ){
			   $column_th_toggle_arr[$columnTHToggleKey] = ( isset( $columnTHToggleVal ) && $columnTHToggleVal == 1 ) ? 1 : 0;
			}
		}
		if( $getMembersColumns ){ //update
			$data = [
				'columns'	=>	maybe_serialize( $column_th_toggle_arr ),
				'_date'		=>	date_i18n('Y-m-d H:i:s'),
			];
			$where = [ 'id' => $getMembersColumns->id ];
			$updating = $wpdb->update( $tableNameCol, $data, $where );
			if( !$updating ){
				$out = array( "error" => 1,'msg' => __('Update faild',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
			}
		}else{ //insert
			$data = [
				'email'		=>	$refAccount,
				'columns'	=>	maybe_serialize( $column_th_toggle_arr ),
				'_date'		=>	date_i18n('Y-m-d H:i:s'),
			];
			$inserting = $wpdb->insert( $tableNameCol, $data );
			if( !$inserting ){
				$out = array( "error" => 1,'msg' => __('Update failed',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('admin_post_export_smtokenholder_act','cip_export_smtokenholder_act_callback');
function cip_export_smtokenholder_act_callback() {
    global $wpdb;

    // Log the export action
    $log_type = 'export_holder';
    $user = wp_get_current_user();
    create_cip_logs_entery($user->ID, $log_type);

    // Set the file name and headers for CSV download
    $file_name = 'CSRHolder-' . date_i18n('d-m-Y H-i-s') . '.csv';
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $file_name . '"');
    header('Pragma: no-cache');
    header('Expires: 0');

    // Open the output stream for writing to the browser
    $output = fopen('php://output', 'w');

    // Column headers for the CSV
    $columnHeader = array('reference', 'eth_address', 'occurs_times', 'csr_amount_initial', 'csramount_by_ethaddress', 'csr_amount_issued', 'amount_due', 'username', 'csramount_byusername', 'occurs_times_user', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', '_user_status', 'kyc_status', 'pool_ref', 'approvedkyc', 'corp_approved', 'notes_external', 'notes_internal', 'Position', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'note_1', 'note_2', 'note_3', 'note_4', 'note_5', 'note_6', 'note_7', 'note_8', 'note_9', 'note_10', 'imported_by', 'import_at', 'last_update_at', 'saved_amount', 'saving_date', 'saving_start_date', 'saving_interest', 'saving_periods', 'saving_state', 'sign_verify', 'transhash', 'contract_address', 'receiver_address', 'ma_enabled', 'token');
    fputcsv($output, $columnHeader);

    // Define the batch size
    $batch_size = 100000;
    $offset = 0;

    // Loop through and fetch data in batches, processing each batch
    while (true) {
        // Fetch a batch of records from the database
        $getTHsData = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}token_holder LIMIT %d OFFSET %d", $batch_size, $offset));

        // If no data is returned, break the loop
        if (empty($getTHsData)) {
            break;
        }

        // Process each row and output it to the CSV file
        foreach ($getTHsData as $getTHData) {
            // Format the dates if necessary
            $redemption_date_formatted = $getTHData->redemption_date ? DateTime::createFromFormat('d/m/Y', $getTHData->redemption_date)->format('d/m/Y') : '';
            $claim_date_formatted = $getTHData->claim_date ? DateTime::createFromFormat('d/m/Y', $getTHData->claim_date)->format('d/m/Y') : '';

            // Prepare the data row for the CSV
            $rowData = array(
                $getTHData->reference, $getTHData->eth_address, $getTHData->occurs_times, $getTHData->csr_amount_initial, $getTHData->csramount_by_ethaddress, $getTHData->csr_amount_issued, $getTHData->amount_due, $getTHData->username, $getTHData->csramount_byusername, $getTHData->occurs_times_user,
                $getTHData->first_name, $getTHData->last_name, $redemption_date_formatted, $claim_date_formatted, $getTHData->email, $getTHData->_user_status, $getTHData->kyc_status, $getTHData->pool_ref, $getTHData->approvedkyc, $getTHData->corp_approved,
                $getTHData->notes_external, $getTHData->notes_internal, $getTHData->position, $getTHData->text_1, $getTHData->text_2, $getTHData->text_3, $getTHData->text_4, $getTHData->text_5, $getTHData->text_6, $getTHData->text_7, $getTHData->text_8,
                $getTHData->text_9, $getTHData->text_10, $getTHData->date_1, $getTHData->date_2, $getTHData->date_3, $getTHData->date_4, $getTHData->date_5, $getTHData->date_6, $getTHData->date_7, $getTHData->date_8, $getTHData->date_9, $getTHData->date_10,
                $getTHData->int_1, $getTHData->int_2, $getTHData->int_3, $getTHData->int_4, $getTHData->int_5, $getTHData->int_6, $getTHData->int_7, $getTHData->int_8, $getTHData->int_9, $getTHData->int_10, $getTHData->note_1, $getTHData->note_2,
                $getTHData->note_3, $getTHData->note_4, $getTHData->note_5, $getTHData->note_6, $getTHData->note_7, $getTHData->note_8, $getTHData->note_9, $getTHData->note_10, $getTHData->imported_by, $getTHData->import_at, $getTHData->last_update_at,
                $getTHData->saved_amount, $getTHData->saving_date, $getTHData->saving_start_date, $getTHData->saving_interest, $getTHData->saving_periods, $getTHData->saving_state, $getTHData->sign_verify, $getTHData->transhash, $getTHData->contract_address,
                $getTHData->receiver_address, $getTHData->ma_enabled, $getTHData->token
            );

            // Write the row to the CSV file
            fputcsv($output, $rowData);
        }

        // Increase the offset for the next batch
        $offset += $batch_size;
    }

    // Close the output stream after all data has been processed
    fclose($output);
    $current_user = wp_get_current_user();
    $logs = sprintf( __('CSR Holder download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
    exit;
}
add_action('admin_post_export_smmemberinvoice_act','cip_export_smmemberinvoice_act_callback');
function cip_export_smmemberinvoice_act_callback(){
	$log_type = 'export_invoice';
	$user = wp_get_current_user();
	create_cip_logs_entery( $user->ID, $log_type );
	include('PHPExcel/Classes/PHPExcel.php');
	include('PHPExcel/Classes/PHPExcel/IOFactory.php');
	$objPHPExcel = new PHPExcel();
	$objPHPExcel->getProperties()->setCreator("CIP Helper")
		->setLastModifiedBy("CIP Helper")
		->setTitle("CIP Helper")
		->setSubject("CIP Helper")
		->setDescription("CIP Helper")
		->setKeywords("CIP Helper")
		->setCategory("CIP Helper");
	global $wpdb;
	$sheetCounter = 0;
	$tableName = $wpdb->prefix . 'cip_member_invoice';
	$getMIsData = $wpdb->get_results("SELECT * FROM $tableName");
	$objPHPExcel->setActiveSheetIndex( $sheetCounter );
	$objPHPExcel->getActiveSheet()->setTitle(__('CIP Member Invoice',CIP_TXTDOMAIN));
	$excelRow = 2;
	$objPHPExcel->getActiveSheet()->setCellValue('A1', 'PO Number');
	$objPHPExcel->getActiveSheet()->setCellValue('B1', 'Date');
	$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Invoice Number');
	$objPHPExcel->getActiveSheet()->setCellValue('D1', 'Paid Date');
	$objPHPExcel->getActiveSheet()->setCellValue('E1', 'Status');
	$objPHPExcel->getActiveSheet()->setCellValue('F1', 'Amplivo username');
	$objPHPExcel->getActiveSheet()->setCellValue('G1', 'First Name');
	$objPHPExcel->getActiveSheet()->setCellValue('H1', 'Last Name');
	$objPHPExcel->getActiveSheet()->setCellValue('I1', 'Email');
	$objPHPExcel->getActiveSheet()->setCellValue('J1', 'Sponsor ID');
	$objPHPExcel->getActiveSheet()->setCellValue('K1', 'Net Amount');
	$objPHPExcel->getActiveSheet()->setCellValue('L1', 'VAT Amount');
	$objPHPExcel->getActiveSheet()->setCellValue('M1', 'Gross Amount');
	$objPHPExcel->getActiveSheet()->setCellValue('N1', 'Vat Number');
	$objPHPExcel->getActiveSheet()->setCellValue('O1', 'Business Name');
	$objPHPExcel->getActiveSheet()->setCellValue('P1', 'Country');
	$objPHPExcel->getActiveSheet()->setCellValue('Q1', 'Address1');
	$objPHPExcel->getActiveSheet()->setCellValue('R1', 'Address2');
	$objPHPExcel->getActiveSheet()->setCellValue('S1', 'City');
	$objPHPExcel->getActiveSheet()->setCellValue('T1', 'State');
	$objPHPExcel->getActiveSheet()->setCellValue('U1', 'Zipcode');
	$objPHPExcel->getActiveSheet()->setCellValue('V1', 'token');
	foreach( $getMIsData as $getMIData ){
		$objPHPExcel->getActiveSheet()->setCellValue('A'.$excelRow, $getMIData->ProformaInvoiceNumber);
		$objPHPExcel->getActiveSheet()->setCellValue('B'.$excelRow, $getMIData->Date);
		$objPHPExcel->getActiveSheet()->setCellValue('C'.$excelRow, $getMIData->InvoiceNumber);
		$objPHPExcel->getActiveSheet()->setCellValue('D'.$excelRow, $getMIData->PaidDate);
		$objPHPExcel->getActiveSheet()->setCellValue('E'.$excelRow, $getMIData->Status);
		$objPHPExcel->getActiveSheet()->setCellValue('F'.$excelRow, $getMIData->Username);
		$objPHPExcel->getActiveSheet()->setCellValue('G'.$excelRow, $getMIData->FirstName);
		$objPHPExcel->getActiveSheet()->setCellValue('H'.$excelRow, $getMIData->LastName);
		$objPHPExcel->getActiveSheet()->setCellValue('I'.$excelRow, $getMIData->Email);
		$objPHPExcel->getActiveSheet()->setCellValue('J'.$excelRow, $getMIData->IntroducedBy);
		$objPHPExcel->getActiveSheet()->setCellValue('K'.$excelRow, $getMIData->GrossAmount);
		$objPHPExcel->getActiveSheet()->setCellValue('L'.$excelRow, $getMIData->VATAmount);
		$objPHPExcel->getActiveSheet()->setCellValue('M'.$excelRow, $getMIData->NetAmount);
		$objPHPExcel->getActiveSheet()->setCellValue('N'.$excelRow, $getMIData->VatNumber);
		$objPHPExcel->getActiveSheet()->setCellValue('O'.$excelRow, $getMIData->BusinessName);
		$objPHPExcel->getActiveSheet()->setCellValue('P'.$excelRow, $getMIData->Country);
		$objPHPExcel->getActiveSheet()->setCellValue('Q'.$excelRow, $getMIData->Address1 );
		$objPHPExcel->getActiveSheet()->setCellValue('R'.$excelRow, $getMIData->Address2 );
		$objPHPExcel->getActiveSheet()->setCellValue('S'.$excelRow, $getMIData->City);
		$objPHPExcel->getActiveSheet()->setCellValue('T'.$excelRow, $getMIData->State );
		$objPHPExcel->getActiveSheet()->setCellValue('U'.$excelRow, $getMIData->Zipcode );
		$objPHPExcel->getActiveSheet()->setCellValue('V'.$excelRow, $getMIData->token);
		$excelRow++;
	}

	PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
	// $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
	$current_user = wp_get_current_user();
	$logs = sprintf( __('CSR Member invoices download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
	$file_name = 'CIPMemberInvoices-'.date_i18n('d-m-Y H-i-s');
	header('Content-type: application/vnd.ms-excel');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	$objWriter->save('php://output');
	exit;
}
add_action('wp_ajax_cip_sm_import_csv_act','cip_sm_import_csv_act_callback');
function cip_sm_import_csv_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMthimportMSYxCIP_' ) ){
		if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['is_fieldmap'] ) && $_POST['is_fieldmap'] == 'yes' ) ){ // field mapping
			$column_html = "";
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$file = $_FILES['th_csv_file']['tmp_name'];
				include( 'PHPExcel/Classes/PHPExcel/IOFactory.php' );
				$inputFileName = $file;
				try {
					$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objReader->setInputEncoding('ISO-8859-1');
					$objPHPExcel = $objReader->load($inputFileName);
				}catch(Exception $e){
					$out = array( "error" => 1,'msg' => $e->getMessage() );
					echo wp_json_encode( $out );
					exit;
				}
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow();
				$highestColumn = $sheet->getHighestColumn();
				$row = 1;
				$row2 = 2;
				$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
				$columnsArr = [
					'reference'					=> __('Reference',CIP_TXTDOMAIN),
					'eth_address'				=> __('ETH Address',CIP_TXTDOMAIN),
					'occurs_times'				=> __('Occurs times',CIP_TXTDOMAIN),
					'csr_amount_initial'		=> __('CSR Amount Initial',CIP_TXTDOMAIN),
					'csramount_by_ethaddress'	=> __('CSR amount. By ETH address',CIP_TXTDOMAIN),
					'csr_amount_issued'			=> __('CSR Amount Issued',CIP_TXTDOMAIN),
					'amount_due'				=> __('Amount due',CIP_TXTDOMAIN),
					'username'					=> __('Username',CIP_TXTDOMAIN),
					'csramount_byusername'		=> __('CSR amount. By username',CIP_TXTDOMAIN),
					'occurs_times_user'			=> __('Occurs times. By username',CIP_TXTDOMAIN),
					'first_name'				=> __('First Name',CIP_TXTDOMAIN),
					'last_name'					=> __('Last Name',CIP_TXTDOMAIN),
					'redemption_date'			=> __('Redemption Date',CIP_TXTDOMAIN),
					'claim_date'				=> __('Claim Date',CIP_TXTDOMAIN),
					'email'						=> __('Email',CIP_TXTDOMAIN),
					'_user_status'				=> __('User Status',CIP_TXTDOMAIN),
					'kyc_status'				=> __('KYC Status',CIP_TXTDOMAIN),
					'pool_ref'					=> __('Pool Ref',CIP_TXTDOMAIN),
					'approvedkyc'				=> __('Approved KYC/Invalid Docs',CIP_TXTDOMAIN),
					'corp_approved'				=> __('Corp Approved',CIP_TXTDOMAIN),
					'notes_external'			=> __('Notes (External for member)',CIP_TXTDOMAIN),
					'notes_internal'			=> __('Notes (Internal Private)',CIP_TXTDOMAIN),
					'position'					=> __('Position',CIP_TXTDOMAIN),
					'text_1'					=>	__('text_1',CIP_TXTDOMAIN),
					'text_2'					=>	__('text_2',CIP_TXTDOMAIN),
					'text_3'					=>	__('text_3',CIP_TXTDOMAIN),
					'text_4'					=>	__('text_4',CIP_TXTDOMAIN),
					'text_5'					=>	__('text_5',CIP_TXTDOMAIN),
					'text_6'					=>	__('text_6',CIP_TXTDOMAIN),
					'text_7'					=>	__('text_7',CIP_TXTDOMAIN),
					'text_8'					=>	__('text_8',CIP_TXTDOMAIN),
					'text_9'					=>	__('text_9',CIP_TXTDOMAIN),
					'text_10'					=>	__('text_10',CIP_TXTDOMAIN),
					'date_1'					=>	__('date_1',CIP_TXTDOMAIN),
					'date_2'					=>	__('date_2',CIP_TXTDOMAIN),
					'date_3'					=>	__('date_3',CIP_TXTDOMAIN),
					'date_4'					=>	__('date_4',CIP_TXTDOMAIN),
					'date_5'					=>	__('date_5',CIP_TXTDOMAIN),
					'date_6'					=>	__('date_6',CIP_TXTDOMAIN),
					'date_7'					=>	__('date_7',CIP_TXTDOMAIN),
					'date_8'					=>	__('date_8',CIP_TXTDOMAIN),
					'date_9'					=>	__('date_9',CIP_TXTDOMAIN),
					'date_10'					=>	__('date_10',CIP_TXTDOMAIN),
					'int_1'						=>	__('int_1',CIP_TXTDOMAIN),
					'int_2'						=>	__('int_2',CIP_TXTDOMAIN),
					'int_3'						=>	__('int_3',CIP_TXTDOMAIN),
					'int_4'						=>	__('int_4',CIP_TXTDOMAIN),
					'int_5'						=>	__('int_5',CIP_TXTDOMAIN),
					'int_6'						=>	__('int_6',CIP_TXTDOMAIN),
					'int_7'						=>	__('int_7',CIP_TXTDOMAIN),
					'int_8'						=>	__('int_8',CIP_TXTDOMAIN),
					'int_9'						=>	__('int_9',CIP_TXTDOMAIN),
					'int_10'					=>	__('int_10',CIP_TXTDOMAIN),
					'note_1'					=>	__('note_1',CIP_TXTDOMAIN),
					'note_2'					=>	__('note_2',CIP_TXTDOMAIN),
					'note_3'					=>	__('note_3',CIP_TXTDOMAIN),
					'note_4'					=>	__('note_4',CIP_TXTDOMAIN),
					'note_5'					=>	__('note_5',CIP_TXTDOMAIN),
					'note_6'					=>	__('note_6',CIP_TXTDOMAIN),
					'note_7'					=>	__('note_7',CIP_TXTDOMAIN),
					'note_8'					=>	__('note_8',CIP_TXTDOMAIN),
					'note_9'					=>	__('note_9',CIP_TXTDOMAIN),
					'note_10'					=>	__('note_10',CIP_TXTDOMAIN),
					'imported_by'				=>	__('imported_by',CIP_TXTDOMAIN),
					'import_at'					=>	__('import_at',CIP_TXTDOMAIN),
					'last_update_at'			=>	__('last_update_at',CIP_TXTDOMAIN),
					'saved_amount'				=>	__('Saved Amount',CIP_TXTDOMAIN),
					'saving_date'				=>	__('Saved Date',CIP_TXTDOMAIN),
					'saving_start_date'			=>	__('Saving Start Date',CIP_TXTDOMAIN),
					'saving_interest'			=>	__('Saving Interest',CIP_TXTDOMAIN),
					'saving_periods'			=>	__('Saving Periods',CIP_TXTDOMAIN),
					'saving_state'				=>	__('Saving State',CIP_TXTDOMAIN),
					'sign_verify'				=>	__('Sign Verify',CIP_TXTDOMAIN),
					'transhash'					=>	__('Trans Hash',CIP_TXTDOMAIN),
					'contract_address'			=>	__('Contract Address',CIP_TXTDOMAIN),
					'receiver_address'			=>	__('Receiver Address',CIP_TXTDOMAIN),
					'ma_enabled'				=>	__('MA Enabled',CIP_TXTDOMAIN),
					'token'						=>	__('Token',CIP_TXTDOMAIN),
				];
				$column_html .= '<div class="row">';
				$columnsArrCount = 0;
				foreach( $columnsArr as $key => $columnField ){
					// $first_word = explode(' ',trim($columnField));
					$first_word = $columnField;
					$required = '';
					if( $key == 0 ){
						$required = 'required';
					}
					$column_html .= '<div class="col-4"><label>' . $columnField . '</label>';
					$column_html .= '<select name="fieldmap_col_' . $columnsArrCount . '" ' . $required . ' >';
					$column_html .= '<option value="">------</option>';
					if( !empty( $rowData[0] ) ){
						foreach( $rowData[0] as $colKey => $column ){
							if( strtolower($column) == strtolower($key) ){
								$column_html .= '<option value="'.$colKey.'" selected>' . $column . '</option>';
							}else{
								$column_html .= '<option value="'.$colKey.'">' . $column . '</option>';
							}
						}
					}
					$column_html .= '</select>';
					$column_html .= '</div>';
					$columnsArrCount++;
				}
				$column_html .= '</div>';
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $column_html, 'highestRow' => ( $highestRow - 1 ) );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['is_csv_split'] ) && $_POST['is_csv_split'] == 'yes' ) ){
			global $table_prefix, $wpdb;
			$thTable = $table_prefix . 'token_holder';

			//==================================================//
			// cip_clear_logs();
			$csvFile = CIP_PLUGIN_BASE.'/'.'thcsv_'.$_POST['is_csv_split_id'].'.csv';
			$start_time = microtime(true);
			if (($handle = fopen($csvFile, 'r')) !== false) {
				$flag = true;
				$rowDataCount= 0;
				$countError = 0;
				$countSuccess = 0;
				cip_clear_logs();
				while (($rowData = fgetcsv($handle, 0)) !== false) {
					// if($flag) { $flag = false; continue; }
					$rowError = false;
					$start_time_loop = microtime(true);
					$countTotalRun++;

					$reference = ( $rowData[ $_POST['fieldmap_col_0'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_0'] ] : '';
					$eth_address = ( $rowData[ $_POST['fieldmap_col_1'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_1'] ] : '';
					$occurs_times = ( $rowData[ $_POST['fieldmap_col_2'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_2'] ] : '';
					$csr_amount_initial = ( $rowData[ $_POST['fieldmap_col_3'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_3'] ] : '';
					$csramount_by_ethaddress = ( $rowData[ $_POST['fieldmap_col_4'] ] != "" ) ? str_replace( ',', '', $rowData[ $_POST['fieldmap_col_4'] ]) : '';
					$csr_amount_issued = ( $rowData[ $_POST['fieldmap_col_5'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_5'] ] : '';
					$amount_due = ( $rowData[ $_POST['fieldmap_col_6'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_6'] ] : '';
					$username = ( $rowData[ $_POST['fieldmap_col_7'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_7'] ] : '';
					// $username = iconv('UTF-8', 'windows-1252', $username);
					$csramount_byusername = ( $rowData[ $_POST['fieldmap_col_8'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_8'] ] : '';
					$occurs_times_user = ( $rowData[ $_POST['fieldmap_col_9'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_9'] ] : '';
					$first_name = ( $rowData[ $_POST['fieldmap_col_10'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_10'] ] : '';
					// $first_name = iconv('UTF-8', 'windows-1252', $first_name);
					$last_name = ( $rowData[ $_POST['fieldmap_col_11'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_11'] ] : '';
					// $last_name = iconv('UTF-8', 'windows-1252', $last_name);
					$redemption_date = ( $rowData[ $_POST['fieldmap_col_12'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_12'] ] : '';
					$claim_date = ( $rowData[ $_POST['fieldmap_col_13'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_13'] ] : '';
					$email = ( $rowData[ $_POST['fieldmap_col_14'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_14'] ] : '';
					$user_status = ( $rowData[ $_POST['fieldmap_col_15'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_15'] ] : '';
					$kyc_status = ( $rowData[ $_POST['fieldmap_col_16'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_16'] ] : '';
					$pool_ref = ( $rowData[ $_POST['fieldmap_col_17'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_17'] ] : '';
					$approvedkyc = ( $rowData[ $_POST['fieldmap_col_18'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_18'] ] : '';
					$corp_approved = ( $rowData[ $_POST['fieldmap_col_19'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_19'] ] : '';
					$notes_external = ( $rowData[ $_POST['fieldmap_col_20'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_20'] ] : '';
					$notes_internal = ( $rowData[ $_POST['fieldmap_col_21'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_21'] ] : '';
					$position = ( $rowData[ $_POST['fieldmap_col_22'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_22'] ] : null;

					$text_1 = ( $rowData[ $_POST['fieldmap_col_23'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_23'] ] : null;
					$text_2 = ( $rowData[ $_POST['fieldmap_col_24'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_24'] ] : null;
					$text_3 = ( $rowData[ $_POST['fieldmap_col_25'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_25'] ] : null;
					$text_4 = ( $rowData[ $_POST['fieldmap_col_26'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_26'] ] : null;
					$text_5 = ( $rowData[ $_POST['fieldmap_col_27'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_27'] ] : null;
					$text_6 = ( $rowData[ $_POST['fieldmap_col_28'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_28'] ] : null;
					$text_7 = ( $rowData[ $_POST['fieldmap_col_29'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_29'] ] : null;
					$text_8 = ( $rowData[ $_POST['fieldmap_col_30'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_30'] ] : null;
					$text_9 = ( $rowData[ $_POST['fieldmap_col_31'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_31'] ] : null;
					$text_10 = ( $rowData[ $_POST['fieldmap_col_32'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_32'] ] : null;
					$date_1 = ( $rowData[ $_POST['fieldmap_col_33'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_33'] ] : null;
					$date_2 = ( $rowData[ $_POST['fieldmap_col_34'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_34'] ] : null;
					$date_3 = ( $rowData[ $_POST['fieldmap_col_35'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_35'] ] : null;
					$date_4 = ( $rowData[ $_POST['fieldmap_col_36'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_36'] ] : null;
					$date_5 = ( $rowData[ $_POST['fieldmap_col_37'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_37'] ] : null;
					$date_6 = ( $rowData[ $_POST['fieldmap_col_38'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_38'] ] : null;
					$date_7 = ( $rowData[ $_POST['fieldmap_col_39'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_39'] ] : null;
					$date_8 = ( $rowData[ $_POST['fieldmap_col_40'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_40'] ] : null;
					$date_9 = ( $rowData[ $_POST['fieldmap_col_41'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_41'] ] : null;
					$date_10 = ( $rowData[ $_POST['fieldmap_col_42'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_42'] ] : null;
					$int_1 = ( $rowData[ $_POST['fieldmap_col_43'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_43'] ] : null;
					$int_2 = ( $rowData[ $_POST['fieldmap_col_44'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_44'] ] : null;
					$int_3 = ( $rowData[ $_POST['fieldmap_col_45'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_45'] ] : null;
					$int_4 = ( $rowData[ $_POST['fieldmap_col_46'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_46'] ] : null;
					$int_5 = ( $rowData[ $_POST['fieldmap_col_47'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_47'] ] : null;
					$int_6 = ( $rowData[ $_POST['fieldmap_col_48'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_48'] ] : null;
					$int_7 = ( $rowData[ $_POST['fieldmap_col_49'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_49'] ] : null;
					$int_8 = ( $rowData[ $_POST['fieldmap_col_50'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_50'] ] : null;
					$int_9 = ( $rowData[ $_POST['fieldmap_col_51'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_51'] ] : null;
					$int_10 = ( $rowData[ $_POST['fieldmap_col_52'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_52'] ] : null;
					$note_1 = ( $rowData[ $_POST['fieldmap_col_53'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_53'] ] : null;
					$note_2 = ( $rowData[ $_POST['fieldmap_col_54'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_54'] ] : null;
					$note_3 = ( $rowData[ $_POST['fieldmap_col_55'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_55'] ] : null;
					$note_4 = ( $rowData[ $_POST['fieldmap_col_56'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_56'] ] : null;
					$note_5 = ( $rowData[ $_POST['fieldmap_col_57'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_57'] ] : null;
					$note_6 = ( $rowData[ $_POST['fieldmap_col_58'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_58'] ] : null;
					$note_7 = ( $rowData[ $_POST['fieldmap_col_59'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_59'] ] : null;
					$note_8 = ( $rowData[ $_POST['fieldmap_col_60'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_60'] ] : null;
					$note_9 = ( $rowData[ $_POST['fieldmap_col_61'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_61'] ] : null;
					$note_10 = ( $rowData[ $_POST['fieldmap_col_62'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_62'] ] : null;

					$imported_by = ( $rowData[ $_POST['fieldmap_col_63'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_63'] ] : 0;
					$import_at = ( $rowData[ $_POST['fieldmap_col_64'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_64'] ] : null;
					$last_update_at = ( $rowData[ $_POST['fieldmap_col_65'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_65'] ] : null;
					$saved_amount = ( $rowData[ $_POST['fieldmap_col_66'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_66'] ] : null;
					$saving_date = ( $rowData[ $_POST['fieldmap_col_67'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_67'] ] : null;
					$saving_start_date = ( $rowData[ $_POST['fieldmap_col_68'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_68'] ] : null;
					$saving_interest = ( $rowData[ $_POST['fieldmap_col_69'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_69'] ] : null;
					$saving_periods = ( $rowData[ $_POST['fieldmap_col_70'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_70'] ] : null;
					$saving_state = ( $rowData[ $_POST['fieldmap_col_71'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_71'] ] : null;
					$sign_verify = ( $rowData[ $_POST['fieldmap_col_72'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_72'] ] : null;
					$transhash = ( $rowData[ $_POST['fieldmap_col_73'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_73'] ] : null;
					$contract_address = ( $rowData[ $_POST['fieldmap_col_74'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_74'] ] : null;
					$receiver_address = ( $rowData[ $_POST['fieldmap_col_75'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_75'] ] : null;
					$ma_enabled = ( $rowData[ $_POST['fieldmap_col_76'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_76'] ] : 0;
					$token = ( $rowData[ $_POST['fieldmap_col_77'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_77'] ] : "CSR";

					// $rowRawString = '<tr class="%s"><th scope="row">%s</th><td>%s</td><td>%s</td></tr>';

					// $getRefData = $wpdb->get_row("SELECT id,reference FROM $thTable WHERE reference = '".$reference."' ");
					// $getRefData = $wpdb->get_var("SELECT COUNT(id),reference FROM $thTable WHERE reference = '".$reference."' ");
					// if( $getRefData ){
					if( false ){
						$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('skipped, Duplicate entry found',CIP_TXTDOMAIN) );
						$log_msg = $row . ' :: ' . $reference . ' :: failed ' . __('skipped, Duplicate entry found',CIP_TXTDOMAIN);
						// cip_create_logs( $log_msg );
						// cip_create_logs( $log_msg , true );
						$countError++;
						// $_SESSION['countError'] = $countError;
						break;
					}else{
						$validationError = [];
						if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
							$rowError = true;
							$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
						}
						if( !empty( $occurs_times ) && !is_numeric( $occurs_times ) ){
							$rowError = true;
							$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csramount_by_ethaddress ) && !is_numeric( $csramount_by_ethaddress ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $amount_due ) && !is_numeric( $amount_due ) ){
							$rowError = true;
							$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csramount_byusername ) && !is_numeric( $csramount_byusername ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csr_amount_issued ) && !is_numeric( $csr_amount_issued ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $occurs_times_user ) && !is_numeric( $occurs_times_user ) ){
							$rowError = true;
							$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $redemption_date ) && DateTime::createFromFormat('d/m/Y', $redemption_date) === false ){
							$rowError = true;
							$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
						}
						if( !empty( $claim_date ) && DateTime::createFromFormat('d/m/Y', $claim_date) === false ){
							$rowError = true;
							$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
						}
						if( $rowError === true ){
							// $logs .= sprintf( $rowRawString, $trDanger, $row, $reference, implode(', ', $validationError) );
							$log_msg = $row . ' :: ' . $reference . ' :: failed ' . implode(', ', $validationError);
							// cip_create_logs( $log_msg );
							cip_create_logs( $log_msg , true );
							$countError++;
							// $_SESSION['countError'] = $countError;
							break;
							// continue;
						}
						$redemption_date_formatted = "";
						$claim_date_formatted = "";
						if( $redemption_date ){
							$formattedRDate = DateTime::createFromFormat('d/m/Y', $redemption_date);
							if( $formattedRDate ){
								$redemption_date_formatted = $formattedRDate->format('d/m/Y');
							}
						}
						if( $claim_date ){
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $claim_date);
							if( $formattedCDate ){
								$claim_date_formatted = $formattedCDate->format('d/m/Y');
							}
						}
						$data = [
							'reference'					=>	wp_strip_all_tags( $reference ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'occurs_times'				=>	wp_strip_all_tags( $occurs_times ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'csramount_by_ethaddress'	=>	wp_strip_all_tags( $csramount_by_ethaddress ),
							'csr_amount_issued'			=>	wp_strip_all_tags( $csr_amount_issued ),
							'amount_due'				=>	wp_strip_all_tags( $amount_due ),
							'username'					=>	wp_strip_all_tags( wp_unslash( $username ) ),
							'csramount_byusername'		=>	wp_strip_all_tags( $csramount_byusername ),
							'occurs_times_user'			=>	wp_strip_all_tags( $occurs_times_user ),
							'first_name'				=>	wp_strip_all_tags( wp_unslash( $first_name ) ),
							'last_name'					=>	wp_strip_all_tags( wp_unslash( $last_name ) ),
							'redemption_date'			=>	wp_strip_all_tags( $redemption_date_formatted ),
							'claim_date'				=>	wp_strip_all_tags( $claim_date_formatted ),
							'email'						=>	wp_strip_all_tags( $email ),
							'_user_status'				=>	wp_strip_all_tags( $user_status ),
							'kyc_status'				=>	wp_strip_all_tags( $kyc_status ),
							'pool_ref'					=>	wp_strip_all_tags( $pool_ref ),
							'approvedkyc'				=>	wp_strip_all_tags( $approvedkyc ),
							'corp_approved'				=>	wp_strip_all_tags( $corp_approved ),
							'notes_external'			=>	wp_strip_all_tags( wp_unslash( $notes_external ) ),
							'notes_internal'			=>	wp_strip_all_tags( wp_unslash( $notes_internal ) ),
							'position'					=>	$position,
							'text_1'					=>	wp_strip_all_tags( $text_1 ),
							'text_2'					=>	wp_strip_all_tags( $text_2 ),
							'text_3'					=>	wp_strip_all_tags( $text_3 ),
							'text_4'					=>	wp_strip_all_tags( $text_4 ),
							'text_5'					=>	wp_strip_all_tags( $text_5 ),
							'text_6'					=>	wp_strip_all_tags( $text_6 ),
							'text_7'					=>	wp_strip_all_tags( $text_7 ),
							'text_8'					=>	wp_strip_all_tags( $text_8 ),
							'text_9'					=>	wp_strip_all_tags( $text_9 ),
							'text_10'					=>	wp_strip_all_tags( $text_10 ),
							'date_1'					=>	wp_strip_all_tags( $date_1 ),
							'date_2'					=>	wp_strip_all_tags( $date_2 ),
							'date_3'					=>	wp_strip_all_tags( $date_3 ),
							'date_4'					=>	wp_strip_all_tags( $date_4 ),
							'date_5'					=>	wp_strip_all_tags( $date_5 ),
							'date_6'					=>	wp_strip_all_tags( $date_6 ),
							'date_7'					=>	wp_strip_all_tags( $date_7 ),
							'date_8'					=>	wp_strip_all_tags( $date_8 ),
							'date_9'					=>	wp_strip_all_tags( $date_9 ),
							'date_10'					=>	wp_strip_all_tags( $date_10 ),
							'int_1'						=>	wp_strip_all_tags( $int_1 ),
							'int_2'						=>	wp_strip_all_tags( $int_2 ),
							'int_3'						=>	wp_strip_all_tags( $int_3 ),
							'int_4'						=>	wp_strip_all_tags( $int_4 ),
							'int_5'						=>	wp_strip_all_tags( $int_5 ),
							'int_6'						=>	wp_strip_all_tags( $int_6 ),
							'int_7'						=>	wp_strip_all_tags( $int_7 ),
							'int_8'						=>	wp_strip_all_tags( $int_8 ),
							'int_9'						=>	wp_strip_all_tags( $int_9 ),
							'int_10'					=>	wp_strip_all_tags( $int_10 ),
							'note_1'					=>	wp_strip_all_tags( $note_1 ),
							'note_2'					=>	wp_strip_all_tags( $note_2 ),
							'note_3'					=>	wp_strip_all_tags( $note_3 ),
							'note_4'					=>	wp_strip_all_tags( $note_4 ),
							'note_5'					=>	wp_strip_all_tags( $note_5 ),
							'note_6'					=>	wp_strip_all_tags( $note_6 ),
							'note_7'					=>	wp_strip_all_tags( $note_7 ),
							'note_8'					=>	wp_strip_all_tags( $note_8 ),
							'note_9'					=>	wp_strip_all_tags( $note_9 ),
							'note_10'					=>	wp_strip_all_tags( $note_10 ),
							'imported_by'				=>	$imported_by,
							'import_at'					=>	$import_at,
							'last_update_at'			=>	$last_update_at,
							'saved_amount'				=>	$saved_amount,
							'saving_date'				=>	$saving_date,
							'saving_start_date'			=>	$saving_start_date,
							'saving_interest'			=>	$saving_interest,
							'saving_periods'			=>	$saving_periods,
							'saving_state'				=>	$saving_state,
							'sign_verify'				=>	$sign_verify,
							'transhash'					=>	$transhash,
							'contract_address'			=>	$contract_address,
							'receiver_address'			=>	$receiver_address,
							'ma_enabled'				=>	$ma_enabled,
							'token'						=>	$token,
						];
						$inserting = $wpdb->insert( $thTable, $data );
						if( $inserting ){
							// $logs .= sprintf( $rowRawString, $trSuccess, $row, $reference, __('inserted',CIP_TXTDOMAIN) );
							$log_msg = $row . ' :: ' . $reference . ' :: ' . __('inserted',CIP_TXTDOMAIN);
							cip_create_logs( $log_msg );
							$countSuccess++;
							// $_SESSION['countSuccess'] = $countSuccess;
						}else{
							// $logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('failed',CIP_TXTDOMAIN) );
							$log_msg = $row . ' :: ' . $reference . ' :: ' . __('failed ',CIP_TXTDOMAIN) . $wpdb->last_error;
							$countError++;
							// $_SESSION['countError'] = $countError;
							// cip_create_logs( $log_msg );
							cip_create_logs( $log_msg , true );
							break;
						}
					}

				}
				fclose($handle);
				unlink($csvFile);
			}
			// $wpdb->flush();
			$end_time = microtime(true);
			$execution_time = ($end_time - $start_time);
			$filename = 'cip_exec_time.log';
			$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a");
			fwrite($file, " Execution time of script = ".$execution_time." sec :: ".date_i18n('d.m.Y H:i:s') . "\n");
			fclose($file);
			//==================================================//

			$log_type = 'import_csv';
			$user = wp_get_current_user();
			// create_cip_logs_entery( $user->ID, $log_type );
			if( $countSuccess > 0 ){
				$successRowText = sprintf( _n( '%s row', '%s rows', $countSuccess, CIP_TXTDOMAIN ), $countSuccess );
			}else{
				$successRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countSuccess );
			}
			if( $countError > 0 ){
				$failedRowText = sprintf( _n( '%s row', '%s rows', $countError, CIP_TXTDOMAIN ), $countError );
			}else{
				$failedRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countError );
			}
			$importNoticeMsg = sprintf( __('%s imported and %s failed',CIP_TXTDOMAIN), $successRowText, $failedRowText );
			/* if( !empty( $logs ) ){
				$logTable = '<style>.table-success tbody+tbody, .table-success td, .table-success th, .table-success thead th{border-color: #8fd19e;}.table-success, .table-success>td, .table-success>th{background-color: #84d897 !important;}.table-danger tbody+tbody, .table-danger td, .table-danger th, .table-danger thead th{border-color: #ed969e !important;}.table-danger, .table-danger>td, .table-danger>th{background-color: #f5c6cb !important;}</style><div class="row"><div class="col-md-12 text-center mb-1"><button type="button" class="btn btn-info mr-5" id="show_all">show all</button><button type="button" class="btn btn-info" id="error_all">show errors</button></div><div class="col-md-12 text-center mb-1"><h4>'.$importNoticeMsg.'</h4></div></div>';
			} */
			$totalInsertedCount = $wpdb->get_var("SELECT COUNT(id) FROM $thTable");
			$importNoticeMsg .= ' ,'.sprintf( __('Total imported : %s',CIP_TXTDOMAIN), $totalInsertedCount );
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'logs' => '<h4>'.$importNoticeMsg.'</h4>', 'countSuccess' => $countSuccess, 'countError' => $countError ,'totalInsertedCount' => $totalInsertedCount );
			$current_user = wp_get_current_user();
			$logs = sprintf( __('Import Holder Data by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );

		}else{ // importing data
			$batchsize = 50000;
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$csv_file = $_FILES['th_csv_file']['tmp_name'];

				global $table_prefix, $wpdb;
				$thTable = $table_prefix . 'token_holder';

				if(($handle = fopen($csv_file, 'r')) !== FALSE) {
					set_time_limit(0);
					$row = 0;
					$fileCounter = 0;
					$flag = true;
					while(($data = fgetcsv($handle)) !== FALSE) {
						if($flag) { $flag = false; continue; }
						$col_count = count($data);
						//splitting of CSV file :
						if ($row % $batchsize == 0):
							$file = fopen(CIP_PLUGIN_BASE.'/'."thcsv_$fileCounter.csv","w");
							$fileCounter++;
						endif;
						$json = implode(',', $data);
						fwrite($file,$json.PHP_EOL);
						//sending the splitted CSV files, batch by batch...
						if ($row % $batchsize == 0):
							// echo "senddata('thcsv_$fileCounter.csv');";
						endif;
						$row++;
					}
					fclose($file);
					fclose($handle);
				}

				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'loopcount' => $fileCounter );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//paritial import token holder
add_action('wp_ajax_cip_sm_partial_import_csv_act','cip_sm_partial_import_csv_act_callback');
function cip_sm_partial_import_csv_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMPartialthimportMSYxCIP_' ) ){
		if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['is_fieldmap'] ) && $_POST['is_fieldmap'] == 'yes' ) ){ // field mapping
			$column_html = "";
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$file = $_FILES['th_csv_file']['tmp_name'];
				include( 'PHPExcel/Classes/PHPExcel/IOFactory.php' );
				$inputFileName = $file;
				try {
					$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objReader->setInputEncoding('ISO-8859-1');
					$objPHPExcel = $objReader->load($inputFileName);
				}catch(Exception $e){
					$out = array( "error" => 1,'msg' => $e->getMessage() );
					echo wp_json_encode( $out );
					exit;
				}
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow();
				$highestColumn = $sheet->getHighestColumn();
				$row = 1;
				$row2 = 2;
				$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
				$columnsArr = [
					'reference'					=> __('Reference',CIP_TXTDOMAIN),
					'eth_address'				=> __('ETH Address',CIP_TXTDOMAIN),
					'occurs_times'				=> __('Occurs times',CIP_TXTDOMAIN),
					'csr_amount_initial'		=> __('CSR Amount Initial',CIP_TXTDOMAIN),
					'csramount_by_ethaddress'	=> __('CSR amount. By ETH address',CIP_TXTDOMAIN),
					'csr_amount_issued'			=> __('CSR Amount Issued',CIP_TXTDOMAIN),
					'amount_due'				=> __('Amount due',CIP_TXTDOMAIN),
					'username'					=> __('Username',CIP_TXTDOMAIN),
					'csramount_byusername'		=> __('CSR amount. By username',CIP_TXTDOMAIN),
					'occurs_times_user'			=> __('Occurs times. By username',CIP_TXTDOMAIN),
					'first_name'				=> __('First Name',CIP_TXTDOMAIN),
					'last_name'					=> __('Last Name',CIP_TXTDOMAIN),
					'redemption_date'			=> __('Redemption Date',CIP_TXTDOMAIN),
					'claim_date'				=> __('Claim Date',CIP_TXTDOMAIN),
					'email'						=> __('Email',CIP_TXTDOMAIN),
					'_user_status'				=> __('User Status',CIP_TXTDOMAIN),
					'kyc_status'				=> __('KYC Status',CIP_TXTDOMAIN),
					'pool_ref'					=> __('Pool Ref',CIP_TXTDOMAIN),
					'approvedkyc'				=> __('Approved KYC/Invalid Docs',CIP_TXTDOMAIN),
					'corp_approved'				=> __('Corp Approved',CIP_TXTDOMAIN),
					'notes_external'			=> __('Notes (External for member)',CIP_TXTDOMAIN),
					'notes_internal'			=> __('Notes (Internal Private)',CIP_TXTDOMAIN),
					'position'					=> __('Position',CIP_TXTDOMAIN),
					'text_1'					=>	__('text_1',CIP_TXTDOMAIN),
					'text_2'					=>	__('text_2',CIP_TXTDOMAIN),
					'text_3'					=>	__('text_3',CIP_TXTDOMAIN),
					'text_4'					=>	__('text_4',CIP_TXTDOMAIN),
					'text_5'					=>	__('text_5',CIP_TXTDOMAIN),
					'text_6'					=>	__('text_6',CIP_TXTDOMAIN),
					'text_7'					=>	__('text_7',CIP_TXTDOMAIN),
					'text_8'					=>	__('text_8',CIP_TXTDOMAIN),
					'text_9'					=>	__('text_9',CIP_TXTDOMAIN),
					'text_10'					=>	__('text_10',CIP_TXTDOMAIN),
					'date_1'					=>	__('date_1',CIP_TXTDOMAIN),
					'date_2'					=>	__('date_2',CIP_TXTDOMAIN),
					'date_3'					=>	__('date_3',CIP_TXTDOMAIN),
					'date_4'					=>	__('date_4',CIP_TXTDOMAIN),
					'date_5'					=>	__('date_5',CIP_TXTDOMAIN),
					'date_6'					=>	__('date_6',CIP_TXTDOMAIN),
					'date_7'					=>	__('date_7',CIP_TXTDOMAIN),
					'date_8'					=>	__('date_8',CIP_TXTDOMAIN),
					'date_9'					=>	__('date_9',CIP_TXTDOMAIN),
					'date_10'					=>	__('date_10',CIP_TXTDOMAIN),
					'int_1'						=>	__('int_1',CIP_TXTDOMAIN),
					'int_2'						=>	__('int_2',CIP_TXTDOMAIN),
					'int_3'						=>	__('int_3',CIP_TXTDOMAIN),
					'int_4'						=>	__('int_4',CIP_TXTDOMAIN),
					'int_5'						=>	__('int_5',CIP_TXTDOMAIN),
					'int_6'						=>	__('int_6',CIP_TXTDOMAIN),
					'int_7'						=>	__('int_7',CIP_TXTDOMAIN),
					'int_8'						=>	__('int_8',CIP_TXTDOMAIN),
					'int_9'						=>	__('int_9',CIP_TXTDOMAIN),
					'int_10'					=>	__('int_10',CIP_TXTDOMAIN),
					'note_1'					=>	__('note_1',CIP_TXTDOMAIN),
					'note_2'					=>	__('note_2',CIP_TXTDOMAIN),
					'note_3'					=>	__('note_3',CIP_TXTDOMAIN),
					'note_4'					=>	__('note_4',CIP_TXTDOMAIN),
					'note_5'					=>	__('note_5',CIP_TXTDOMAIN),
					'note_6'					=>	__('note_6',CIP_TXTDOMAIN),
					'note_7'					=>	__('note_7',CIP_TXTDOMAIN),
					'note_8'					=>	__('note_8',CIP_TXTDOMAIN),
					'note_9'					=>	__('note_9',CIP_TXTDOMAIN),
					'note_10'					=>	__('note_10',CIP_TXTDOMAIN),
					'imported_by'				=>	__('imported_by',CIP_TXTDOMAIN),
					'import_at'					=>	__('import_at',CIP_TXTDOMAIN),
					'last_update_at'			=>	__('last_update_at',CIP_TXTDOMAIN),
					'saved_amount'				=>	__('Saved Amount',CIP_TXTDOMAIN),
					'saving_date'				=>	__('Saved Date',CIP_TXTDOMAIN),
					'saving_start_date'			=>	__('Saving Start Date',CIP_TXTDOMAIN),
					'saving_interest'			=>	__('Saving Interest',CIP_TXTDOMAIN),
					'saving_periods'			=>	__('Saving Periods',CIP_TXTDOMAIN),
					'saving_state'				=>	__('Saving State',CIP_TXTDOMAIN),
					'sign_verify'				=>	__('Sign Verify',CIP_TXTDOMAIN),
					'transhash'					=>	__('Trans Hash',CIP_TXTDOMAIN),
					'contract_address'			=>	__('Contract Address',CIP_TXTDOMAIN),
					'receiver_address'			=>	__('Receiver Address',CIP_TXTDOMAIN),
					'ma_enabled'				=>	__('MA Enabled',CIP_TXTDOMAIN),
					'token'						=>	__('Token',CIP_TXTDOMAIN),
				];
				$column_html .= '<div class="row">';
				$columnsArrCount = 0;
				foreach( $columnsArr as $key => $columnField ){
					// $first_word = explode(' ',trim($columnField));
					$first_word = $columnField;
					$required = '';
					if( $key == 0 ){
						$required = 'required';
					}
					$column_html .= '<div class="col-4"><label>' . $columnField . '</label>';
					$column_html .= '<select name="fieldmap_col_' . $columnsArrCount . '" ' . $required . ' >';
					$column_html .= '<option value="">------</option>';
					if( !empty( $rowData[0] ) ){
						foreach( $rowData[0] as $colKey => $column ){
							if( strtolower($column) == strtolower($key) ){
								$column_html .= '<option value="'.$colKey.'" selected>' . $column . '</option>';
							}else{
								$column_html .= '<option value="'.$colKey.'">' . $column . '</option>';
							}
						}
					}
					$column_html .= '</select>';
					$column_html .= '</div>';
					$columnsArrCount++;
				}
				$column_html .= '</div>';
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $column_html, 'highestRow' => ( $highestRow - 1 ) );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['is_csv_split'] ) && $_POST['is_csv_split'] == 'yes' ) ){
			global $table_prefix, $wpdb;
			$thTable = $table_prefix . 'token_holder';

			//==================================================//
			// cip_clear_logs();
			$csvFile = CIP_PLUGIN_BASE.'/'.'thcsv_'.$_POST['is_csv_split_id'].'.csv';
			$start_time = microtime(true);
			if (($handle = fopen($csvFile, 'r')) !== false) {
				$flag = true;
				$rowDataCount= 0;
				$countError = 0;
				$countSuccess = 0;
				cip_clear_logs();
				while (($rowData = fgetcsv($handle, 0)) !== false) {
					// if($flag) { $flag = false; continue; }
					$rowError = false;
					$start_time_loop = microtime(true);
					$countTotalRun++;

					$reference = ( $rowData[ $_POST['fieldmap_col_0'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_0'] ] : '0';
					$eth_address = ( $rowData[ $_POST['fieldmap_col_1'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_1'] ] : '';
					$occurs_times = ( $rowData[ $_POST['fieldmap_col_2'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_2'] ] : '';
					$csr_amount_initial = ( $rowData[ $_POST['fieldmap_col_3'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_3'] ] : '';
					$csramount_by_ethaddress = ( $rowData[ $_POST['fieldmap_col_4'] ] != "" ) ? str_replace( ',', '', $rowData[ $_POST['fieldmap_col_4'] ]) : '';
					$csr_amount_issued = ( $rowData[ $_POST['fieldmap_col_5'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_5'] ] : '';
					$amount_due = ( $rowData[ $_POST['fieldmap_col_6'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_6'] ] : '';
					$username = ( $rowData[ $_POST['fieldmap_col_7'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_7'] ] : '';
					// $username = iconv('UTF-8', 'windows-1252', $username);
					$csramount_byusername = ( $rowData[ $_POST['fieldmap_col_8'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_8'] ] : '';
					$occurs_times_user = ( $rowData[ $_POST['fieldmap_col_9'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_9'] ] : '';
					$first_name = ( $rowData[ $_POST['fieldmap_col_10'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_10'] ] : '';
					// $first_name = iconv('UTF-8', 'windows-1252', $first_name);
					$last_name = ( $rowData[ $_POST['fieldmap_col_11'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_11'] ] : '';
					// $last_name = iconv('UTF-8', 'windows-1252', $last_name);
					$redemption_date = ( $rowData[ $_POST['fieldmap_col_12'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_12'] ] : '';
					$claim_date = ( $rowData[ $_POST['fieldmap_col_13'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_13'] ] : '';
					$email = ( $rowData[ $_POST['fieldmap_col_14'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_14'] ] : '';
					$user_status = ( $rowData[ $_POST['fieldmap_col_15'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_15'] ] : '';
					$kyc_status = ( $rowData[ $_POST['fieldmap_col_16'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_16'] ] : '';
					$pool_ref = ( $rowData[ $_POST['fieldmap_col_17'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_17'] ] : '';
					$approvedkyc = ( $rowData[ $_POST['fieldmap_col_18'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_18'] ] : '';
					$corp_approved = ( $rowData[ $_POST['fieldmap_col_19'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_19'] ] : '';
					$notes_external = ( $rowData[ $_POST['fieldmap_col_20'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_20'] ] : '';
					$notes_internal = ( $rowData[ $_POST['fieldmap_col_21'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_21'] ] : '';
					$position = ( $rowData[ $_POST['fieldmap_col_22'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_22'] ] : null;

					$text_1 = ( $rowData[ $_POST['fieldmap_col_23'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_23'] ] : null;
					$text_2 = ( $rowData[ $_POST['fieldmap_col_24'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_24'] ] : null;
					$text_3 = ( $rowData[ $_POST['fieldmap_col_25'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_25'] ] : null;
					$text_4 = ( $rowData[ $_POST['fieldmap_col_26'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_26'] ] : null;
					$text_5 = ( $rowData[ $_POST['fieldmap_col_27'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_27'] ] : null;
					$text_6 = ( $rowData[ $_POST['fieldmap_col_28'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_28'] ] : null;
					$text_7 = ( $rowData[ $_POST['fieldmap_col_29'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_29'] ] : null;
					$text_8 = ( $rowData[ $_POST['fieldmap_col_30'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_30'] ] : null;
					$text_9 = ( $rowData[ $_POST['fieldmap_col_31'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_31'] ] : null;
					$text_10 = ( $rowData[ $_POST['fieldmap_col_32'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_32'] ] : null;
					$date_1 = ( $rowData[ $_POST['fieldmap_col_33'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_33'] ] : null;
					$date_2 = ( $rowData[ $_POST['fieldmap_col_34'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_34'] ] : null;
					$date_3 = ( $rowData[ $_POST['fieldmap_col_35'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_35'] ] : null;
					$date_4 = ( $rowData[ $_POST['fieldmap_col_36'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_36'] ] : null;
					$date_5 = ( $rowData[ $_POST['fieldmap_col_37'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_37'] ] : null;
					$date_6 = ( $rowData[ $_POST['fieldmap_col_38'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_38'] ] : null;
					$date_7 = ( $rowData[ $_POST['fieldmap_col_39'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_39'] ] : null;
					$date_8 = ( $rowData[ $_POST['fieldmap_col_40'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_40'] ] : null;
					$date_9 = ( $rowData[ $_POST['fieldmap_col_41'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_41'] ] : null;
					$date_10 = ( $rowData[ $_POST['fieldmap_col_42'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_42'] ] : null;
					$int_1 = ( $rowData[ $_POST['fieldmap_col_43'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_43'] ] : null;
					$int_2 = ( $rowData[ $_POST['fieldmap_col_44'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_44'] ] : null;
					$int_3 = ( $rowData[ $_POST['fieldmap_col_45'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_45'] ] : null;
					$int_4 = ( $rowData[ $_POST['fieldmap_col_46'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_46'] ] : null;
					$int_5 = ( $rowData[ $_POST['fieldmap_col_47'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_47'] ] : null;
					$int_6 = ( $rowData[ $_POST['fieldmap_col_48'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_48'] ] : null;
					$int_7 = ( $rowData[ $_POST['fieldmap_col_49'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_49'] ] : null;
					$int_8 = ( $rowData[ $_POST['fieldmap_col_50'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_50'] ] : null;
					$int_9 = ( $rowData[ $_POST['fieldmap_col_51'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_51'] ] : null;
					$int_10 = ( $rowData[ $_POST['fieldmap_col_52'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_52'] ] : null;
					$note_1 = ( $rowData[ $_POST['fieldmap_col_53'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_53'] ] : null;
					$note_2 = ( $rowData[ $_POST['fieldmap_col_54'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_54'] ] : null;
					$note_3 = ( $rowData[ $_POST['fieldmap_col_55'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_55'] ] : null;
					$note_4 = ( $rowData[ $_POST['fieldmap_col_56'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_56'] ] : null;
					$note_5 = ( $rowData[ $_POST['fieldmap_col_57'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_57'] ] : null;
					$note_6 = ( $rowData[ $_POST['fieldmap_col_58'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_58'] ] : null;
					$note_7 = ( $rowData[ $_POST['fieldmap_col_59'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_59'] ] : null;
					$note_8 = ( $rowData[ $_POST['fieldmap_col_60'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_60'] ] : null;
					$note_9 = ( $rowData[ $_POST['fieldmap_col_61'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_61'] ] : null;
					$note_10 = ( $rowData[ $_POST['fieldmap_col_62'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_62'] ] : null;

					$imported_by = ( $rowData[ $_POST['fieldmap_col_63'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_63'] ] : 0;
					$import_at = ( $rowData[ $_POST['fieldmap_col_64'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_64'] ] : null;
					$last_update_at = ( $rowData[ $_POST['fieldmap_col_65'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_65'] ] : null;
					$saved_amount = ( $rowData[ $_POST['fieldmap_col_66'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_66'] ] : null;
					$saving_date = ( $rowData[ $_POST['fieldmap_col_67'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_67'] ] : null;
					$saving_start_date = ( $rowData[ $_POST['fieldmap_col_68'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_68'] ] : null;
					$saving_interest = ( $rowData[ $_POST['fieldmap_col_69'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_69'] ] : null;
					$saving_periods = ( $rowData[ $_POST['fieldmap_col_70'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_70'] ] : null;
					$saving_state = ( $rowData[ $_POST['fieldmap_col_71'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_71'] ] : null;
					$sign_verify = ( $rowData[ $_POST['fieldmap_col_72'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_72'] ] : null;
					$transhash = ( $rowData[ $_POST['fieldmap_col_73'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_73'] ] : null;
					$contract_address = ( $rowData[ $_POST['fieldmap_col_74'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_74'] ] : null;
					$receiver_address = ( $rowData[ $_POST['fieldmap_col_75'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_75'] ] : null;
					$ma_enabled = ( $rowData[ $_POST['fieldmap_col_76'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_76'] ] : 0;
					$token = ( $rowData[ $_POST['fieldmap_col_77'] ] != "" ) ? $rowData[ $_POST['fieldmap_col_77'] ] : "CSR";

					$getRefData = $wpdb->get_row("SELECT id,reference FROM $thTable WHERE reference = '".$reference."' ");
					/* if( $getRefData ){
						$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('skipped, Duplicate entry found',CIP_TXTDOMAIN) );
						$log_msg = $row . ' :: ' . $reference . ' :: failed ' . __('skipped, Duplicate entry found',CIP_TXTDOMAIN);
						cip_create_logs( $log_msg , true );
						$countError++;
						break;
					}else{ */
						$validationError = [];
						if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
							$rowError = true;
							$validationError[] = __('Email is invalid',CIP_TXTDOMAIN);
						}
						if( !empty( $occurs_times ) && !is_numeric( $occurs_times ) ){
							$rowError = true;
							$validationError[] = __('Occurs times is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csramount_by_ethaddress ) && !is_numeric( $csramount_by_ethaddress ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by ETH Address is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Initial is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $amount_due ) && !is_numeric( $amount_due ) ){
							$rowError = true;
							$validationError[] = __('Amount due is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csramount_byusername ) && !is_numeric( $csramount_byusername ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount by username is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $csr_amount_issued ) && !is_numeric( $csr_amount_issued ) ){
							$rowError = true;
							$validationError[] = __('CSR Amount Issued is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $occurs_times_user ) && !is_numeric( $occurs_times_user ) ){
							$rowError = true;
							$validationError[] = __('Occurs times by user is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $redemption_date ) && DateTime::createFromFormat('d/m/Y', $redemption_date) === false ){
							$rowError = true;
							$validationError[] = __('Redemption date invalid format',CIP_TXTDOMAIN);
						}
						if( !empty( $claim_date ) && DateTime::createFromFormat('d/m/Y', $claim_date) === false ){
							$rowError = true;
							$validationError[] = __('Claim date invalid format',CIP_TXTDOMAIN);
						}
						if( $rowError === true ){
							// $logs .= sprintf( $rowRawString, $trDanger, $row, $reference, implode(', ', $validationError) );
							$log_msg = $row . ' :: ' . $reference . ' :: failed ' . implode(', ', $validationError);
							// cip_create_logs( $log_msg );
							cip_create_logs( $log_msg , true );
							$countError++;
							// $_SESSION['countError'] = $countError;
							break;
							// continue;
						}
						$redemption_date_formatted = "";
						$claim_date_formatted = "";
						if( $redemption_date ){
							$formattedRDate = DateTime::createFromFormat('d/m/Y', $redemption_date);
							if( $formattedRDate ){
								$redemption_date_formatted = $formattedRDate->format('d/m/Y');
							}
						}
						if( $claim_date ){
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $claim_date);
							if( $formattedCDate ){
								$claim_date_formatted = $formattedCDate->format('d/m/Y');
							}
						}
						$data = [
							'reference'					=>	wp_strip_all_tags( $reference ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'occurs_times'				=>	wp_strip_all_tags( $occurs_times ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'csramount_by_ethaddress'	=>	wp_strip_all_tags( $csramount_by_ethaddress ),
							'csr_amount_issued'			=>	wp_strip_all_tags( $csr_amount_issued ),
							'amount_due'				=>	wp_strip_all_tags( $amount_due ),
							'username'					=>	wp_strip_all_tags( wp_unslash( $username ) ),
							'csramount_byusername'		=>	wp_strip_all_tags( $csramount_byusername ),
							'occurs_times_user'			=>	wp_strip_all_tags( $occurs_times_user ),
							'first_name'				=>	wp_strip_all_tags( wp_unslash( $first_name ) ),
							'last_name'					=>	wp_strip_all_tags( wp_unslash( $last_name ) ),
							'redemption_date'			=>	wp_strip_all_tags( $redemption_date_formatted ),
							'claim_date'				=>	wp_strip_all_tags( $claim_date_formatted ),
							'email'						=>	wp_strip_all_tags( $email ),
							'_user_status'				=>	wp_strip_all_tags( $user_status ),
							'kyc_status'				=>	wp_strip_all_tags( $kyc_status ),
							'pool_ref'					=>	wp_strip_all_tags( $pool_ref ),
							'approvedkyc'				=>	wp_strip_all_tags( $approvedkyc ),
							'corp_approved'				=>	wp_strip_all_tags( $corp_approved ),
							'notes_external'			=>	wp_strip_all_tags( wp_unslash( $notes_external ) ),
							'notes_internal'			=>	wp_strip_all_tags( wp_unslash( $notes_internal ) ),
							'position'					=>	$position,
							'text_1'					=>	wp_strip_all_tags( $text_1 ),
							'text_2'					=>	wp_strip_all_tags( $text_2 ),
							'text_3'					=>	wp_strip_all_tags( $text_3 ),
							'text_4'					=>	wp_strip_all_tags( $text_4 ),
							'text_5'					=>	wp_strip_all_tags( $text_5 ),
							'text_6'					=>	wp_strip_all_tags( $text_6 ),
							'text_7'					=>	wp_strip_all_tags( $text_7 ),
							'text_8'					=>	wp_strip_all_tags( $text_8 ),
							'text_9'					=>	wp_strip_all_tags( $text_9 ),
							'text_10'					=>	wp_strip_all_tags( $text_10 ),
							'date_1'					=>	wp_strip_all_tags( $date_1 ),
							'date_2'					=>	wp_strip_all_tags( $date_2 ),
							'date_3'					=>	wp_strip_all_tags( $date_3 ),
							'date_4'					=>	wp_strip_all_tags( $date_4 ),
							'date_5'					=>	wp_strip_all_tags( $date_5 ),
							'date_6'					=>	wp_strip_all_tags( $date_6 ),
							'date_7'					=>	wp_strip_all_tags( $date_7 ),
							'date_8'					=>	wp_strip_all_tags( $date_8 ),
							'date_9'					=>	wp_strip_all_tags( $date_9 ),
							'date_10'					=>	wp_strip_all_tags( $date_10 ),
							'int_1'						=>	wp_strip_all_tags( $int_1 ),
							'int_2'						=>	wp_strip_all_tags( $int_2 ),
							'int_3'						=>	wp_strip_all_tags( $int_3 ),
							'int_4'						=>	wp_strip_all_tags( $int_4 ),
							'int_5'						=>	wp_strip_all_tags( $int_5 ),
							'int_6'						=>	wp_strip_all_tags( $int_6 ),
							'int_7'						=>	wp_strip_all_tags( $int_7 ),
							'int_8'						=>	wp_strip_all_tags( $int_8 ),
							'int_9'						=>	wp_strip_all_tags( $int_9 ),
							'int_10'					=>	wp_strip_all_tags( $int_10 ),
							'note_1'					=>	wp_strip_all_tags( $note_1 ),
							'note_2'					=>	wp_strip_all_tags( $note_2 ),
							'note_3'					=>	wp_strip_all_tags( $note_3 ),
							'note_4'					=>	wp_strip_all_tags( $note_4 ),
							'note_5'					=>	wp_strip_all_tags( $note_5 ),
							'note_6'					=>	wp_strip_all_tags( $note_6 ),
							'note_7'					=>	wp_strip_all_tags( $note_7 ),
							'note_8'					=>	wp_strip_all_tags( $note_8 ),
							'note_9'					=>	wp_strip_all_tags( $note_9 ),
							'note_10'					=>	wp_strip_all_tags( $note_10 ),
							'imported_by'				=>	$imported_by,
							'import_at'					=>	$import_at,
							'last_update_at'			=>	$last_update_at,
							'saved_amount'				=>	$saved_amount,
							'saving_date'				=>	$saving_date,
							'saving_start_date'			=>	$saving_start_date,
							'saving_interest'			=>	$saving_interest,
							'saving_periods'			=>	$saving_periods,
							'saving_state'				=>	$saving_state,
							'sign_verify'				=>	$sign_verify,
							'transhash'					=>	$transhash,
							'contract_address'			=>	$contract_address,
							'receiver_address'			=>	$receiver_address,
							'ma_enabled'				=>	$ma_enabled,
							'last_update'				=>	date_i18n('Y-m-d H:i:s'),
							'token'						=>	$token,
						];
						$current_user = wp_get_current_user();
						$getRecordsByref = $wpdb->get_row("SELECT `id`,`reference` FROM $thTable WHERE `reference` = '". $reference ."'");
						if( $getRecordsByref ){
							$where = array( 'reference' => $reference, 'id' => $getRecordsByref->id );
							$update = $wpdb->update( $thTable, $data, $where );
							if( $update ){
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('updated.',CIP_TXTDOMAIN) . ' updated data: '.json_encode( $data );
								cip_create_logs( $log_msg );

								create_cip_logs_entery( $current_user->ID, 'partial import', '','sa', $log_msg .' by '.$current_user->user_email.' at '. date_i18n('d/m/Y H:i A'), true  );
								$countSuccess++;
							}else{
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('update failed ',CIP_TXTDOMAIN) . $wpdb->last_error;
								$countError++;
								cip_create_logs( $log_msg , true );
								create_cip_logs_entery( $current_user->ID, 'partial import', '','sa', $log_msg .' by '.$current_user->user_email.' at '. date_i18n('d/m/Y H:i A'), true  );
								break;
							}
						}else{

							$inserting = $wpdb->insert( $thTable, $data );
							if( $inserting ){
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('inserted',CIP_TXTDOMAIN);
								cip_create_logs( $log_msg );
								create_cip_logs_entery( $current_user->ID, 'partial import', '','sa', $log_msg .' by '.$current_user->user_email.' at '. date_i18n('d/m/Y H:i A'), true  );
								$countSuccess++;
							}else{
								$log_msg = $row . ' :: ' . $reference . ' :: ' . __('failed ',CIP_TXTDOMAIN) . $wpdb->last_error;
								$countError++;
								cip_create_logs( $log_msg , true );
								create_cip_logs_entery( $current_user->ID, 'partial import', '','sa', $log_msg .' by '.$current_user->user_email.' at '. date_i18n('d/m/Y H:i A'), true  );
								break;
							}
						}
					//}

				}
				fclose($handle);
				unlink($csvFile);
			}
			// $wpdb->flush();
			$end_time = microtime(true);
			$execution_time = ($end_time - $start_time);
			$filename = 'cip_exec_time.log';
			$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a");
			fwrite($file, " Execution time of script = ".$execution_time." sec :: ".date_i18n('d.m.Y H:i:s') . "\n");
			fclose($file);
			//==================================================//

			$log_type = 'import_csv';
			$user = wp_get_current_user();
			// create_cip_logs_entery( $user->ID, $log_type );
			if( $countSuccess > 0 ){
				$successRowText = sprintf( _n( '%s row', '%s rows', $countSuccess, CIP_TXTDOMAIN ), $countSuccess );
			}else{
				$successRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countSuccess );
			}
			if( $countError > 0 ){
				$failedRowText = sprintf( _n( '%s row', '%s rows', $countError, CIP_TXTDOMAIN ), $countError );
			}else{
				$failedRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countError );
			}
			$importNoticeMsg = sprintf( __('%s imported and %s failed',CIP_TXTDOMAIN), $successRowText, $failedRowText );
			$totalInsertedCount = $wpdb->get_var("SELECT COUNT(id) FROM $thTable");
			//$importNoticeMsg .= ' ,'.sprintf( __('Total imported : %s',CIP_TXTDOMAIN), $totalInsertedCount );
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'logs' => '<h4>'.$importNoticeMsg.'</h4>', 'countSuccess' => $countSuccess, 'countError' => $countError ,'totalInsertedCount' => $totalInsertedCount );

		}else{ // importing data
			$batchsize = 100;
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['th_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$csv_file = $_FILES['th_csv_file']['tmp_name'];

				global $table_prefix, $wpdb;
				$thTable = $table_prefix . 'token_holder';

				if(($handle = fopen($csv_file, 'r')) !== FALSE) {
					set_time_limit(0);
					$row = 0;
					$fileCounter = 0;
					$flag = true;
					while(($data = fgetcsv($handle)) !== FALSE) {
						if($flag) { $flag = false; continue; }
						$col_count = count($data);
						//splitting of CSV file :
						if ($row % $batchsize == 0):
							$file = fopen(CIP_PLUGIN_BASE.'/'."thcsv_$fileCounter.csv","w");
							$fileCounter++;
						endif;
						$json = implode(',', $data);
						fwrite($file,$json.PHP_EOL);
						//sending the splitted CSV files, batch by batch...
						if ($row % $batchsize == 0):
							// echo "senddata('thcsv_$fileCounter.csv');";
						endif;
						$row++;
					}
					fclose($file);
					fclose($handle);
				}

				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'loopcount' => $fileCounter );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//over paritial import token holder
// add_action('wp_footer','senddata_ajax_async');
function senddata_ajax_async(){
	global $table_prefix, $wpdb;
	$thTable = $table_prefix . 'token_holder';
	echo $getRefData = $wpdb->get_var("SELECT COUNT(id),reference FROM $thTable WHERE reference = '".$reference."' ");
	/*?>
	<script>
	function senddata(filename){
		var file = filename;
		var $form = $('.sm_import_th_frm');
		data.append("is_import_split", 'yes');
		$.ajax({
			type: "POST",
			url: cipscript.ajax_url,
			data: {file},
			async: true,
			success: function(response){
				var obj = $.parseJSON(response);
				console.dir( obj );
			}
		});
	}
	</script>
	<?php*/
}
add_action('wp_ajax_cip_sm_import_mi_csv_act','cip_sm_import_mi_csv_act_callback');
function cip_sm_import_mi_csv_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMmiimportMSYxCIP_' ) ){
		if( isset($_FILES['mi_csv_file']['name']) && !empty($_FILES['mi_csv_file']['name']) ){ // importing data
			$allowed_extension = array('csv');
			$ext = pathinfo($_FILES['mi_csv_file']['name'], PATHINFO_EXTENSION);
			if( in_array($ext, $allowed_extension) ){
				$file = $_FILES['mi_csv_file']['tmp_name'];
				include( 'PHPExcel/Classes/PHPExcel/IOFactory.php' );
				$inputFileName = $file;
				try {
					$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
					$objReader = PHPExcel_IOFactory::createReader($inputFileType);
					$objReader->setInputEncoding('ISO-8859-1');
					$objPHPExcel = $objReader->load($inputFileName);
				}catch(Exception $e){
					$out = array( "error" => 1,'msg' => $e->getMessage() );
					echo wp_json_encode( $out );
					exit;
				}
				global $table_prefix, $wpdb;
				$thTable = $table_prefix . 'cip_member_invoice';
				$sheet = $objPHPExcel->getSheet(0);
				$highestRow = $sheet->getHighestRow();
				$highestColumn = $sheet->getHighestColumn();
				$count = 2;
				$trDanger = "table-danger";
				$trSuccess = "table-success";
				$logs = "";
				$countError = 0;
				$countSuccess = 0;
				cip_clear_logs();
				for($row = 2; $row <= $highestRow; $row++){
					$rowError = false;
					$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
					$ProformaInvoiceNumber = ( $rowData[0][0] != "" ) ? $rowData[0][0] : null;
					$Date = ( $rowData[0][1] != "" ) ? $rowData[0][1] : null;
					$InvoiceNumber = ( $rowData[0][1] != "" ) ? $rowData[0][1] : null;
					$PaidDate = ( $rowData[0][2] != "" ) ? $rowData[0][2] : null;
					$Status = ( $rowData[0][3] != "" ) ? $rowData[0][3] : null;
					$Username = ( $rowData[0][4] != "" ) ? $rowData[0][4] : null;
					$FirstName = ( $rowData[0][5] != "" ) ? $rowData[0][5] : null;
					$LastName = ( $rowData[0][6] != "" ) ? $rowData[0][6] : null;
					$Email = ( $rowData[0][7] != "" ) ? $rowData[0][7] : null;
					$IntroducedBy = ( $rowData[0][8] != "" ) ? $rowData[0][8] : null;
					$NetAmount = ( $rowData[0][9] != "" ) ? $rowData[0][9] : null;
					$VATAmount = ( $rowData[0][10] != "" ) ? $rowData[0][10] : null;
					$GrossAmount = ( $rowData[0][11] != "" ) ? $rowData[0][11] : null;
					$VatNumber = ( $rowData[0][12] != "" ) ? $rowData[0][12] : null;
					$BusinessName	 = ( $rowData[0][13] != "" ) ? $rowData[0][13] : null;
					$Country = ( $rowData[0][14] != "" ) ? $rowData[0][14] : null;
					$Address1 = ( $rowData[0][15] != "" ) ? $rowData[0][15] : null;
					$Address2 = ( $rowData[0][16] != "" ) ? $rowData[0][16] : null;
					$City = ( $rowData[0][17] != "" ) ? $rowData[0][17] : null;
					$State = ( $rowData[0][18] != "" ) ? $rowData[0][18] : null;
					$Zipcode = ( $rowData[0][19] != "" ) ? $rowData[0][19] : null;
					$token = ( $rowData[0][20] != "" ) ? $rowData[0][20] : null;

					$rowRawString = '<tr class="%s"><th scope="row">%s</th><td>%s</td><td>%s</td></tr>';
					$data = [
						'ProformaInvoiceNumber'		=>	wp_strip_all_tags( $ProformaInvoiceNumber ),
						'Date'						=>	wp_strip_all_tags( $Date ),
						'InvoiceNumber'				=>	wp_strip_all_tags( $InvoiceNumber ),
						'PaidDate'					=>	wp_strip_all_tags( $PaidDate ),
						'Status'					=>	wp_strip_all_tags( $Status ),
						'Username'					=>	wp_strip_all_tags( $Username ),
						'FirstName'					=>	wp_strip_all_tags( $FirstName ),
						'LastName'					=>	wp_strip_all_tags( $LastName ),
						'Email'						=>	wp_strip_all_tags( $Email ),
						'IntroducedBy'				=>	wp_strip_all_tags( $IntroducedBy ),
						'NetAmount'					=>	wp_strip_all_tags( $NetAmount ),
						'VATAmount'					=>	wp_strip_all_tags( $VATAmount ),
						'GrossAmount'				=>	wp_strip_all_tags( $GrossAmount ),
						'VatNumber'					=>	wp_strip_all_tags( $VatNumber ),
						'BusinessName'				=>	wp_strip_all_tags( $BusinessName ),
						'Country'					=>	wp_strip_all_tags( $Country ),
						'Address1'					=>	wp_strip_all_tags( $Address1 ),
						'Address2'					=>	wp_strip_all_tags( $Address2 ),
						'City'						=>	wp_strip_all_tags( $City ),
						'State'						=>	wp_strip_all_tags( $State ),
						'Zipcode'					=>	wp_strip_all_tags( $Zipcode ),
						'token'						=>	wp_strip_all_tags( $token )
					];
					$inserting = $wpdb->insert( $thTable, $data );
					if( $inserting ){
						$logs .= sprintf( $rowRawString, $trSuccess, $row, $reference, __('inserted',CIP_TXTDOMAIN) );
						$log_msg = $row . ' :: ' . __('inserted',CIP_TXTDOMAIN);
						cip_create_logs( $log_msg );
						$countSuccess++;
					}else{
						$logs .= sprintf( $rowRawString, $trDanger, $row, $reference, __('failed',CIP_TXTDOMAIN) );
						$log_msg = $row . ' :: ' . __('failed',CIP_TXTDOMAIN);
						$countError++;
						cip_create_logs( $log_msg );
					}
				}
				$log_type = 'import_csv';
				$user = wp_get_current_user();
				create_cip_logs_entery( $user->ID, $log_type );
				if( $countSuccess > 0 ){
					$successRowText = sprintf( _n( '%s row', '%s rows', $countSuccess, CIP_TXTDOMAIN ), $countSuccess );
				}else{
					$successRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countSuccess );
				}
				if( $countError > 0 ){
					$failedRowText = sprintf( _n( '%s row', '%s rows', $countError, CIP_TXTDOMAIN ), $countError );
				}else{
					$failedRowText = sprintf( __( '%s row', CIP_TXTDOMAIN ), $countError );
				}
				$importNoticeMsg = sprintf( __('%s imported and %s failed',CIP_TXTDOMAIN), $successRowText, $failedRowText );
				if( !empty( $logs ) ){
					$logTable = '<style>.table-success tbody+tbody, .table-success td, .table-success th, .table-success thead th{border-color: #8fd19e;}.table-success, .table-success>td, .table-success>th{background-color: #84d897 !important;}.table-danger tbody+tbody, .table-danger td, .table-danger th, .table-danger thead th{border-color: #ed969e !important;}.table-danger, .table-danger>td, .table-danger>th{background-color: #f5c6cb !important;}</style><div class="row"><div class="col-md-12 text-center mb-1"><button type="button" class="btn btn-info mr-5" id="show_all">show all</button><button type="button" class="btn btn-info" id="error_all">show errors</button></div><div class="col-md-12 text-center mb-1"><h4>'.$importNoticeMsg.'</h4></div></div><table class="table table-sm table-borderless">
								  <thead>
								    <tr>
								      <th scope="col">#</th>
								      <th scope="col">'.__('Reference',CIP_TXTDOMAIN).'</th>
								      <th scope="col">'.__('Log',CIP_TXTDOMAIN).'</th>
								    </tr>
								  </thead>
								  <tbody>';
					$logTable .= $logs;
					$logTable .= '</tbody>
								</table>';
				}
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'logs' => $logTable );
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid file type',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_routine_maintenance_mode_act','cip_routine_maintenance_mode_act_cb');
function cip_routine_maintenance_mode_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYroutinemaintenancemodeYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$maintenance_mode = 0;
		if( isset($_POST['routine_maintenance_mode']) && !empty( $_POST['routine_maintenance_mode'] ) ){
			$maintenance_mode = 1;
			$local_custom_email_id = get_option('local_custom_email_id');
			if( $local_custom_email_id ){
				$local_user = get_user_by( 'email', $local_custom_email_id );
				if( $local_user ){
					$token = wp_get_session_token();
					 if( $token ){
					 	$sessions = WP_Session_Tokens::get_instance( $local_user->ID );
						$sessions->destroy_all();
					 }
				}
			}
		}
		$log_type = 'maintenance';
		$extra_val = ( $maintenance_mode ) ? __('activate',CIP_TXTDOMAIN) : __('deactivate',CIP_TXTDOMAIN) ;
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type , $extra_val );
		update_option( 'cip_routine_maintenance_mode', $maintenance_mode );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// MEMBER MAINTENANCE MODE
add_action('wp_ajax_member_maintenance_mode_act','cip_member_maintenance_mode_act_cb');
function cip_member_maintenance_mode_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYmember_maintenance_modeYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$maintenance_mode = 0;
		if( isset($_POST['member_maintenance_mode']) && !empty( $_POST['member_maintenance_mode'] ) ){
			$maintenance_mode = 1;
			$local_custom_email_id = get_option('local_custom_email_id');
			if( $local_custom_email_id ){
				$local_user = get_user_by( 'email', $local_custom_email_id );
				if( $local_user ){
					$token = wp_get_session_token();
					 if( $token ){
					 	$sessions = WP_Session_Tokens::get_instance( $local_user->ID );
						$sessions->destroy_all();
					 }
				}
			}
		}
		$log_type = 'member maintenance';
		$extra_val = ( $maintenance_mode ) ? __('activate',CIP_TXTDOMAIN) : __('deactivate',CIP_TXTDOMAIN) ;
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type , $extra_val );
		update_option( 'cip_member_maintenance_mode', $maintenance_mode );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// SITE MAINTENANCE MODE
add_action('wp_ajax_site_maintenance_mode_act','cip_site_maintenance_mode_act_cb');
function cip_site_maintenance_mode_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_sitemicro'],'_XYsite_maintenance_modeYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$maintenance_mode = 0;
		if( isset($_POST['site_maintenance_mode']) && !empty( $_POST['site_maintenance_mode'] ) ){
			$maintenance_mode = 1;
			$local_custom_email_id = get_option('local_custom_email_id');
			if( $local_custom_email_id ){
				$local_user = get_user_by( 'email', $local_custom_email_id );
				if( $local_user ){
					$token = wp_get_session_token();
					 if( $token ){
					 	$sessions = WP_Session_Tokens::get_instance( $local_user->ID );
						$sessions->destroy_all();
					 }
				}
			}
		}
		$log_type = 'site maintenance';
		$extra_val = ( $maintenance_mode ) ? __('activate',CIP_TXTDOMAIN) : __('deactivate',CIP_TXTDOMAIN) ;
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type , $extra_val );
		update_option( 'cip_site_maintenance_mode', $maintenance_mode );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_retirement_maintenance_mode_act','cip_retirement_maintenance_mode_act_cb');
function cip_retirement_maintenance_mode_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYretirement_maintenance_modeYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$maintenance_mode = 0;
		if( isset($_POST['retirement_maintenance_mode']) && !empty( $_POST['retirement_maintenance_mode'] ) ){
			$maintenance_mode = 1;
		}
		$log_type = 'retirement maintenance';
		$extra_val = ( $maintenance_mode ) ? __('activate',CIP_TXTDOMAIN) : __('deactivate',CIP_TXTDOMAIN) ;
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type , $extra_val );
		update_option( 'cip_retirement_maintenance_mode', $maintenance_mode );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_smsupport_endpoint_act','cip_smsupport_endpoint_act_cb');
function cip_smsupport_endpoint_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYsmsupportendpointYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		/*$log_type = 'maintenance';
		$extra_val = ( $maintenance_mode ) ? __('activate',CIP_TXTDOMAIN) : __('deactivate',CIP_TXTDOMAIN) ;
		$user = wp_get_current_user();
		create_cip_logs_entery( $user->ID, $log_type , $extra_val );*/
		update_option( 'cip_support_ticket_mode', $_POST['support_ticket_mode'] );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_smthclearmember_act','cip_smthclearmember_act_cb');
function cip_smthclearmember_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYclearsmMembersYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('All data cleared',CIP_TXTDOMAIN) );
			$log_type = 'delete_tbl_holder';
			$user = wp_get_current_user();
			create_cip_logs_entery( $user->ID, $log_type );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_smclearmemberinvoice_act','cip_smclearmemberinvoice_act_cb');
function cip_smclearmemberinvoice_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYclearsmMembersInvoiceYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'cip_member_invoice';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('All data cleared',CIP_TXTDOMAIN) );
			$log_type = 'delete_tbl_mi';
			$user = wp_get_current_user();
			create_cip_logs_entery( $user->ID, $log_type );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function cip_number_format( $number = 0, $decimal = false ){
	if( $decimal ){
		return number_format( $number, 2, '.', '' );
	}else{
		return number_format( $number );
	}
}
function create_cip_logs_entery( $user_id = 0, $log_type = 'member', $extra_val = '', $user_type = 'member', $logs = '' , $islog = true ){ //4966
	global $wpdb;
	$logsTable = $wpdb->prefix . 'cip_logs';
	$userData = get_user_by( 'id', $user_id );

	if( in_array( "supportagent", $userData->roles ) ){
		$user_type = 'sa';
		$islog = true;
	}else if( in_array( "supportmanager", $userData->roles ) ){
		$user_type = 'sm';
		$islog = true;
	}
	if( $islog ){
		$user_roles = $userData->roles;
		$user_role = array_shift($user_roles);

		switch ($log_type) {
			case 'loggedin':
				$logs = sprintf( __('%s (%s) logged in at %s (IP: %s)',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A'), $_SERVER['REMOTE_ADDR'] );
				break;
			case 'loggedout':
				if( empty( $logs ) ){
					$logs = sprintf( __('%s (%s) logged out at %s (IP: %s)',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A'), $_SERVER['REMOTE_ADDR'] );
				}
				break;
			case 'import_csv':
				$logs = sprintf( __('%s (%s) import csv at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
			case 'update_csv':
				$logs = sprintf( __('%s (%s) update csv at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
			case 'update_holder':
				$logs = sprintf( __('%s (%s) update holder at %s. %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A'), $extra_val );
				break;
			case 'delete_holder':
				$logs = sprintf( __('%s (%s) delete holder at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
			case 'update_profile':
				$logs = sprintf( __('%s (%s) update profile at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
			case 'column_update':
				$logs = sprintf( __('%s (%s) column setting update at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;
			case 'export_holder':
				$logs = sprintf( __('%s (%s) export holders at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;

			case 'export_invoice':
				$logs = sprintf( __('%s (%s) export invoices at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;

			case 'import_holder':
				$logs = sprintf( __('%s (%s) import holders at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, date_i18n('d/m/Y H:i A') );
				break;

			case 'maintenance':
				$logs = sprintf( __('%s (%s) %s maintenance mode at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $extra_val, date_i18n('d/m/Y H:i A') );
				break;

			case 'site maintenance':
				$logs = sprintf( __('%s (%s) %s maintenance mode at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $extra_val, date_i18n('d/m/Y H:i A') );
				break;

			case 'member maintenance':
				$logs = sprintf( __('%s (%s) %s member maintenance mode at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $extra_val, date_i18n('d/m/Y H:i A') );
				break;

			case 'delete_tbl_holder':
				$logs = sprintf( __('%s (%s) clear holder records at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $extra_val, date_i18n('d/m/Y H:i A') );
				break;

			case 'delete_tbl_mi':
				$logs = sprintf( __('%s (%s) clear member invoice records at %s',CIP_TXTDOMAIN),$userData->user_email, $user_role, $extra_val, date_i18n('d/m/Y H:i A') );
				break;

		}
		$data = [
			'user_id'	=>	$user_id,
			'user_type'	=>	$user_type,
			'log_type'	=>	$log_type,
			'logs'		=>	$logs,
			'_date'		=>	date_i18n('Y-m-d H:i:s'),
		];
		$wpdb->insert(  $logsTable, $data );
	}
}
add_action( 'wp_login', 'cip_user_loggin_logs_cb', 10, 2 );
function cip_user_loggin_logs_cb( $user_login, WP_User $user ){
	$log_type = 'loggedin';
	create_cip_logs_entery( $user->ID, $log_type );
	sendSmsAlertOnLoggedIn( $user );
	$_SESSION['logged_time'] = time() + get_withdrawal_suspension_option();
	// setcookie('logged_time', time(), time() + 300, "/");
}
add_action( 'clear_auth_cookie', 'cip_user_loggout_logs_cb', 10 );
function cip_user_loggout_logs_cb(){
	$log_type = 'loggedout';
	$user = wp_get_current_user();
	create_cip_logs_entery( $user->ID, $log_type );
}
add_action('wp_head','web3_installing_script');
function web3_installing_script(){
?>
<script type="text/javascript">
	/*web 3 installing*/

	var DataEncrypt = "VHH03XzIO+b1N341d4FIw+YG+XiohgONw+NWWJ0ZVOb+NbHiwP025+x9JHf5sV\/BVTxaC+XH1\/5A0RoLOewfKQ==";
	var DataKey = CryptoJS.enc.Utf8.parse( cryptojs.cipEncki );
	var DataVector = CryptoJS.enc.Utf8.parse( cryptojs.cipEncvct );
	var decrypted = CryptoJS.AES.decrypt(DataEncrypt, DataKey, { iv: DataVector });
	var decrypted = CryptoJS.enc.Utf8.stringify(decrypted);
	// jQuery.getScript("https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js?ver=0.4.2", function() {
		web3 = new Web3(new Web3.providers.HttpProvider( decrypted ));
		//console.log( web3 );
	// });
</script>
<?php
}
add_action('wp_ajax_editethaddressmemberact','cip_editethaddressmemberact_cb');
function cip_editethaddressmemberact_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$refAccountNonce = ( !empty( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : 0 ;
	if( wp_verify_nonce( $_POST['_micro'], $refAccountNonce ) && current_user_can( 'member' ) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		if( $refAccountNonce ){
			$ethNoHaveQry = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '".$_POST['csrwalletaddress']."'");

			if( !$ethNoHaveQry ){ // not have eth at all

				if( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ){ // bulk update

					$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccountNonce."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( date_9 IS NULL OR date_9 = '' ) ");
					if( $getCurrentMembers ){

						$updateEth = false;
						foreach( $getCurrentMembers as $getCurrentMember ){
							if( empty( $getCurrentMember->eth_address ) && !empty( $getCurrentMember->email ) && empty( $getCurrentMember->date_9 ) ){
								if( $refAccountNonce ){
									$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
									$where = [ 'id' => $getCurrentMember->id ];
									$update = $wpdb->update( $tableName, $data, $where );
									if( $update ){
										$updateEth = true;
									}
								}
							}
						}
						if( $updateEth ){
							$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
						}else{
							$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
						}
					}else{
						$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
					}
				}else{	// indvidual update

					$getCurrentMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['_microid']." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccountNonce."' AND ( date_9 IS NULL OR date_9 = '' ) ");
					if( $getCurrentMember ){
						if( $refAccountNonce ){
							$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
							$where = [ 'id' => $_POST['_microid'] ];
							$update = $wpdb->update( $tableName, $data, $where );
							if( $update ){
								$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
							}else{
								$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
							}
						}
					}else{
						$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
					}
				}
			}else{
				$getCsrDataExists = $wpdb->get_results("SELECT * FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email != '".$refAccountNonce."' AND email IS NOT NULL AND email <> '') AND (date_9 IS NOT NULL AND date_9 <> '') ");
				if( $getCsrDataExists ){
					$out = array( "error" => 1, 'msg' => __('<span class="response_error"><br> The CSR Wallet address is alreay added by another user. <br> Please contact support or add new Wallet address.</span>', CIP_TXTDOMAIN) );
				}else{

					$haveOneRecord = $wpdb->get_results("SELECT * FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email = '".$refAccountNonce."' AND email IS NOT NULL AND email <> '') AND (date_10 IS NOT NULL AND date_10 <> '')");
					if( $haveOneRecord ){
						if( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ){ // bulk update

							$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccountNonce."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( date_9 IS NULL OR date_9 = '' ) ");
							if( $getCurrentMembers ){

								$updateEth = false;
								foreach( $getCurrentMembers as $getCurrentMember ){
									if( empty( $getCurrentMember->eth_address ) && !empty( $getCurrentMember->email ) && empty( $getCurrentMember->date_9 ) ){
										if( $refAccountNonce ){
											$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
											$where = [ 'id' => $getCurrentMember->id ];
											$update = $wpdb->update( $tableName, $data, $where );
											if( $update ){
												$updateEth = true;
											}
											//$out = array( "error" => 1,'msg' => $wpdb->last_error );
										}
									}
								}
								if( $updateEth ){
									$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
								}else{
									$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
								}

							}else{
								$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
							}

						}else{	// indvidual update

							$getCurrentMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['_microid']." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccountNonce."' AND ( date_9 IS NULL OR date_9 = '' ) ");

							if( $getCurrentMember ){
								if( $refAccountNonce ){
									$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
									$where = [ 'id' => $_POST['_microid'] ];
									$update = $wpdb->update( $tableName, $data, $where );
									if( $update ){
										$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
									}else{
										$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
									}
								}
							}else{
								$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
							}

						}

					}else{
						$haveOneRecordDate9 = $wpdb->get_results("SELECT * FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email = '".$refAccountNonce."' AND email IS NOT NULL AND email <> '') AND (date_9 IS NOT NULL AND date_9 <> '')");
						if( $haveOneRecordDate9 ){
							if( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ){ // bulk update

								$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccountNonce."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( date_9 IS NULL OR date_9 = '' ) ");
								if( $getCurrentMembers ){

									$updateEth = false;
									foreach( $getCurrentMembers as $getCurrentMember ){
										if( empty( $getCurrentMember->eth_address ) && !empty( $getCurrentMember->email ) && empty( $getCurrentMember->date_9 ) ){
											if( $refAccountNonce ){
												$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
												$where = [ 'id' => $getCurrentMember->id ];
												$update = $wpdb->update( $tableName, $data, $where );
												if( $update ){
													$updateEth = true;
												}
												//$out = array( "error" => 1,'msg' => $wpdb->last_error );
											}
										}
									}
									if( $updateEth ){
										$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
									}else{
										$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
									}

								}else{
									$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
								}

							}else{	// indvidual update

								$getCurrentMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_POST['_microid']." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccountNonce."' AND ( date_9 IS NULL OR date_9 = '' ) ");

								if( $getCurrentMember ){
									if( $refAccountNonce ){
										$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'corp_approved' => 'Pending', 'date_9' => date_i18n('d/m/Y') ];
										$where = [ 'id' => $_POST['_microid'] ];
										$update = $wpdb->update( $tableName, $data, $where );
										if( $update ){
											$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
										}else{
											$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
										}
									}
								}else{
									$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
								}

							}
						}else{
							$out = array( "error" => 1, 'msg' => __('<span class="response_error"><br> The CSR Wallet address is alreay added by another user.<br> Please contact support or add new Wallet address.</span>', CIP_TXTDOMAIN) );
						}
						//$out = array( "error" => 1, 'msg' => __('<span class="response_error"><br> The CSR Wallet address is alreay added by another user. 2<br> Please contact support or add new Wallet address.</span>', CIP_TXTDOMAIN) );
					}


				}
			}
		}

		/*if( $refAccountNonce ){
			$getCsrDataExists = $wpdb->get_results("SELECT * FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email != '".$refAccountNonce."' AND email IS NOT NULL AND email <> '') AND (date_9 IS NOT NULL AND date_9 <> '') ");

			if( $getCsrDataExists ){
				$out = array( "error" => 1, 'msg' => __('<span class="response_error"><br> The CSR Wallet address is alreay added by another user. <br> Please contact support or add new Wallet address.</span>', CIP_TXTDOMAIN) );
			}else{
				if( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ){
					$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE email = '".$refAccountNonce."' AND ( date_9 IS NULL OR date_9 = '' ) ");
					if( $getCurrentMembers ){
						$updateEth = false;
						foreach( $getCurrentMembers as $getCurrentMember ){
							if( empty( $getCurrentMember->eth_address ) && !empty( $getCurrentMember->email ) && empty( $getCurrentMember->date_9 ) ){
								if( $refAccountNonce ){
									$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'date_9' => date_i18n('d/m/Y') ];
									$where = [ 'id' => $getCurrentMember->id ];
									$update = $wpdb->update( $tableName, $data, $where );
									if( $update ){
										$updateEth = true;
									}
									$out = array( "error" => 1,'msg' => $wpdb->last_error );
								}
							}
						}
						if( $updateEth ){
							$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
						}
					}else{
						$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
					}
				}else{
					$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE id = ".$_POST['_microid']." AND email = '".$refAccountNonce."' AND ( date_9 IS NULL OR date_9 = '' ) ");
					if( $getCurrentMembers ){
						if( $refAccountNonce ){
							$data = [ 'eth_address'	=>	$_POST['csrwalletaddress'], 'date_9' => date_i18n('d/m/Y') ];
							$where = [ 'id' => $_POST['_microid'] ];
							$update = $wpdb->update( $tableName, $data, $where );
							if( $update ){
								$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
							}
						}
					}else{
						$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support', CIP_TXTDOMAIN) );
					}
				}
			}
		}*/

	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_proforma_toggle_action','proforma_toggle_action_cb');
function proforma_toggle_action_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $wpdb;
	$date = date_i18n( 'Y-m-d h:i:sa');
	$invoice = $wpdb->prefix . 'cip_member_invoice';
	$invoice_paid = $wpdb->prefix . 'cip_member_invoice_paid';
	$logs = $wpdb->prefix . 'cip_logs';

	$sa_id = get_current_user_id();
	$user = wp_get_current_user();
	$sa_email = $user->user_email;

	$idd=$_POST['id'];
	$ref=$_POST['ref'];
	$status = "Un-Paid";
	$paidDate= date_i18n( 'd-m-Y');
	if($ref == 'Un-Paid'){
		$status = "Paid";
	}

	if( $status == 'Paid' ){
		$invoiceRecordMaxQry = "SELECT * FROM $invoice WHERE `Status` = 'Paid' ORDER BY `InvoiceNumber` DESC";
		$invoiceRecordMaxRecord = $wpdb->get_row($invoiceRecordMaxQry);
		if( $invoiceRecordMaxRecord ){
			$InvoiceNumber = $invoiceRecordMaxRecord->InvoiceNumber + 1;
		}else{
			$InvoiceNumber = 1001;
		}
		$update_account = $wpdb->update( $invoice, ['Status' => $status,'PaidDate' => $paidDate, 'InvoiceNumber' => $InvoiceNumber], ['id' => $idd] );
	}else{
		$update_account = $wpdb->update( $invoice, ['Status' => $status,'PaidDate' => $paidDate], ['id' => $idd] );
	}

	if( $update_account ){
		$data = array(
			'user_id'	=>	$sa_id,
			'user_type'	=>	'sa',
			'log_type'	=>	'Invoice',
			'logs'	=>	sprintf( __('%s(supportagent) Update Invoice Status.',CIP_TXTDOMAIN), $sa_email),
			'_date'	=>	date_i18n('Y-m-d H:i:s'),
		);
		$wpdb->insert( $logs, $data );
		$out = array( "error" => 0, 'status' => $status, 'msg' => __('Updated Successfully.',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// SA ARCHIVE STATUS
add_action('wp_ajax_archive_toggle_action','archive_toggle_action_cb');
function archive_toggle_action_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $wpdb;
	$date = date_i18n( 'Y-m-d h:i:sa');
	$invoice = $wpdb->prefix . 'cip_member_invoice';
	$invoice_paid = $wpdb->prefix . 'cip_member_invoice_paid';
	$logs = $wpdb->prefix . 'cip_logs';

	$sa_id = get_current_user_id();
	$user = wp_get_current_user();
	$sa_email = $user->user_email;

	$idd=$_POST['id'];
	$arch=$_POST['arch'];
	$archive = "No";
	if($arch == 'No'){
		$archive = "Yes";
	}

	if( $archive == 'Yes' ){
		$update_invoice = $wpdb->update( $invoice, ['ArchiveStatus' => $archive], ['id' => $idd] );
	}else{
		$update_invoice = $wpdb->update( $invoice, ['ArchiveStatus' => $archive], ['id' => $idd] );
	}

	if( $update_invoice ){
		$data = array(
			'user_id'	=>	$sa_id,
			'user_type'	=>	'sa',
			'log_type'	=>	'Archive Status',
			'logs'	=>	sprintf( __('%s(supportagent) Update Archieve Status.',CIP_TXTDOMAIN), $sa_email),
			'_date'	=>	date_i18n('Y-m-d H:i:s'),
		);
		$wpdb->insert( $logs, $data );
		$out = array( "error" => 0, 'status' => $archive, 'msg' => __('Updated Successfully.',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// END SA ARCHIVE STATUS
add_filter( 'gform_validation_4', 'custom_vat_validation' );
function custom_vat_validation($validation_result){
    // page 2
    if (GFFormDisplay::get_source_page( 4 ) == 2) {
        $email = rgpost('input_3');
        $vat_number = rgpost( 'input_33');//'102417928';
        $country_code = rgpost( 'input_20'); //EE
        $addressCountry = rgpost( 'input_5_6');
		$countryCode = GF_Fields::get( 'address' )->get_country_code( $addressCountry );
		$introduced_by_product = rgpost( 'input_30');

		if( !empty( $introduced_by_product ) ){
			if( !corsair_get_users_from_sourceapi_byusername( $introduced_by_product )){
				$validation_result['is_valid'] = false;

				foreach ($form['fields'] as &$field) {
					if ($field->id == '30') {
						$field->failed_validation = true;
						$field->validation_message = sprintf(
							__('Invalid "%s" Sponsor ID does not correspond with our records. Please contact the person who referred you to this site. <br/>Proceeding without or with an incorrect Sponsor ID will delay your order.', CIP_TXTDOMAIN),
							esc_html($introduced_by_product)
						);
						$_POST['input_30'] = '';
						break;
					}
				}
			}
		}

		if( $addressCountry == 'United Kingdom' && empty( $vat_number ) ){
			$validation_result['is_valid'] = false;
			$validation_result["form"]["fields"][12]["failed_validation"] = true;
			$validation_result["form"]["fields"][12]["validation_message"] = "Sales to UK consumers are temporarily suspended and they should check back in 7 days";
		}else{
			if( !empty( $vat_number ) ){
				$vatValidateResponse = validating_vat_number_api_callback( $vat_number );

				$form = $validation_result["form"];
				$formData = get_all_gform_fields_value( $form );
				$formData['type']	= 'validate_vat';
				$formData['ip_address']	= cip_get_client_ip();
				global $wpdb;
				$tableLog = $wpdb->prefix.'cip_logs';
				$logData = array(
					'user_id'	=>	0,
					'user_type'	=>	'buyer',
					'log_type'	=>	'api_track',
					'logs'		=>	maybe_serialize( $formData ),
					'_date'		=>	date_i18n('Y-m-d H:i:s'),
				);
				$log_insert = $wpdb->insert( $tableLog, $logData );

				if( !$vatValidateResponse['validate'] ){
					$validation_result['is_valid'] = false;
					$validation_result["form"]["fields"][12]["failed_validation"] = true;
					$validation_result["form"]["fields"][12]["validation_message"] = "VAT number invalid (Check VAT number and VAT Registration Country)";
				}
				if( $vatValidateResponse['validate'] && $vatValidateResponse['country_code'] != $countryCode ){
					$validation_result['is_valid'] = false;
					$validation_result["form"]["fields"][8]["failed_validation"] = true;
					// $validation_result["form"]["fields"][13]["validation_message"] = "VAT Registration Country not match to VAT Number";
					$validation_result["form"]["fields"][8]["validation_message"] = "Address country not match to VAT Number";
				}
			}else{
				$euvatapi_ip_address = ( !empty( get_option('euvatapi_ip_address') ) ) ? get_option('euvatapi_ip_address') : '';
				if( !empty( $euvatapi_ip_address ) ){
					$ip_address = $euvatapi_ip_address;
				}else{
					$ip_address = cip_get_client_ip();
				}
				$vatRateResponse = get_vat_rate_ipaddress_api_callback( $ip_address );

				$form = $validation_result["form"];
				$formData = get_all_gform_fields_value( $form );
				$formData['type']	= 'vat_by_ip';
				$formData['ip_address']	= cip_get_client_ip();
				global $wpdb;
				$tableLog = $wpdb->prefix.'cip_logs';
				$logData = array(
					'user_id'	=>	0,
					'user_type'	=>	'buyer',
					'log_type'	=>	'api_track',
					'logs'		=>	maybe_serialize( $formData ),
					'_date'		=>	date_i18n('Y-m-d H:i:s'),
				);
				$log_insert = $wpdb->insert( $tableLog, $logData );

				if( !$vatRateResponse['success'] ){
					$validation_result['is_valid'] = false;
					$validation_result["form"]["fields"][12]["failed_validation"] = true;
					$validation_result["form"]["fields"][12]["validation_message"] = "There is an issue with external VAT verification... Please try again in 24-48 hours";
				}
			}
		}

		if( !is_user_logged_in() ){
    		$userData = get_user_by( 'email', $email );
    		if( $userData instanceof WP_User ) {
    		    if( $userData ){
    		        if( $userData->user_email == $email ){
    		            $validation_result['is_valid'] = false;
    					$validation_result["form"]["fields"][8]["failed_validation"] = true;
    					$validation_result["form"]["fields"][8]["validation_message"] = __('Email address already registered. Please login to continue', CIP_TXTDOMAIN);
    		        }
    		    }
    		}
		}

    }
    if (GFFormDisplay::get_source_page( 4 ) == 3) {
		if( isset($_COOKIE['buyproductsubmit']) && $_COOKIE['buyproductsubmit'] == 'yes' ){
			$validation_result['is_valid'] = false;
			$validation_result["form"]["fields"][23]["failed_validation"] = true;
			$validation_result["form"]["fields"][23]["validation_message"] = __('Duplicate order detected. Please review your order in the My Purchases section of My CSR. If your order is not listed you can try again by clicking "Become Plastic Neutral"',CIP_TXTDOMAIN);
		}
	}
    return $validation_result;
}
function get_all_gform_fields_value( $form , $entry = array() ){
	$data = array();
	if( $form ){
		foreach($form["fields"] as &$field){
			if (is_array($field["inputs"])){
				foreach($field["inputs"] as &$input){
					$label = $input["label"];
					if( empty( $entry ) ){
						$value = rgpost( "input_{$field['id']}" );
					}else{
						$value = $entry[strval($input["id"])];
					}
					if( !empty( $value ) ){
						$data[ $label ] = $value;
					}
				}
			}else{
				$label = $field["label"];
				if( empty( $entry ) ){
					$value = rgpost( "input_{$field['id']}" );
				}else{
					$value = $entry[$field["id"]];
				}
				if( !empty( $value ) ){
					$data[ $label ] = $value;
				}
			}
		}
	}
	return $data;
}
add_action('wp_head','clear_buy_product_cookie');
function clear_buy_product_cookie(){
	if( is_page( 4258 ) ){
		setcookie('buyproductsubmit', 'no', time() + (86400 / 1440 ) * 15, "/");
	}
}
function viesCheckVAT($countryCode, $vatNumber, $timeout = 30) {
    $response = array ();
    $pattern = '/<(%s).*?>([\s\S]*)<\/\1/';
    $keys = array ('countryCode', 'vatNumber', 'requestDate', 'valid', 'name', 'address');
    $content = "<s11:Envelope xmlns:s11='http://schemas.xmlsoap.org/soap/envelope/'>
  <s11:Body>
    <tns1:checkVat xmlns:tns1='urn:ec.europa.eu:taxud:vies:services:checkVat:types'>
      <tns1:countryCode>%s</tns1:countryCode>
      <tns1:vatNumber>%s</tns1:vatNumber>
    </tns1:checkVat>
  </s11:Body>
</s11:Envelope>";
    $opts = array (
            'http' => array (
                    'method' => 'POST',
                    'header' => "Content-Type: text/xml; charset=utf-8; SOAPAction: checkVatService",
                    'content' => sprintf ( $content, $countryCode, $vatNumber ),
                    'timeout' => $timeout
            )
    );
    $ctx = stream_context_create ( $opts );
    $result = file_get_contents ( 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService', false, $ctx );
    if (preg_match ( sprintf ( $pattern, 'checkVatResponse' ), $result, $matches )) {
        foreach ( $keys as $key )
            preg_match ( sprintf ( $pattern, $key ), $matches [2], $value ) && $response [$key] = $value [2];
    }
    return $response;
}
function validating_vat_number_api_callback( $vat_number = "" ){
	$validateData = array(
		'validate'	=> false,
		'country_code'	=>	'',
		'query'	=>	$vat_number,
	);
	$euvatapi_access_key = ( !empty( get_option('euvatapi_access_key') ) ) ? get_option('euvatapi_access_key') : '9d5cb137a12069fb87aada7a82dc21a3';
	if( !empty( $vat_number ) ){
		$endpoint = add_query_arg( array(
			'access_key' => $euvatapi_access_key,
			'vat_number' => $vat_number,
		), 'https://euvatapi.com/api/v1/validate' );
		$error_msg = "";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $endpoint);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($curl);
		if (curl_errno($curl)) {
			$error_msg = curl_error($curl);
		}
		$responseData = json_decode($response, true);
		curl_close($curl);
		if( empty( $error_msg ) ){
			if( $responseData['valid'] == true ){
				$validateData['validate'] = true;
				$validateData['country_code'] = $responseData['country_code'];
				$validateData['query'] = $responseData['query'];
			}
		}
	}
	return $validateData;
}
function get_vat_rate_ipaddress_api_callback( $ip_address = "" ){
	$validateData = array(
		'success'	=> false,
		'country_code'	=>	'',
		'standard_rate'	=>	null,
	);
	$euvatapi_access_key = ( !empty( get_option('euvatapi_access_key') ) ) ? get_option('euvatapi_access_key') : '9d5cb137a12069fb87aada7a82dc21a3';
	if( !empty( $ip_address ) ){
		$endpoint = add_query_arg( array(
			'access_key' => $euvatapi_access_key,
			'ip_address' => $ip_address,
		), 'https://euvatapi.com/api/v1/rate' );
		$error_msg = "";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $endpoint);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($curl);
		if (curl_errno($curl)) {
			$error_msg = curl_error($curl);
		}
		$responseData = json_decode($response, true);
		curl_close($curl);
		if( empty( $error_msg ) ){
			if( $responseData['success'] == true ){
				$validateData['success'] = true;
				$validateData['country_code'] = $responseData['country_code'];
				$validateData['standard_rate'] = $responseData['standard_rate'];
			}
		}
	}
	return $validateData;
}
function get_vat_rate_code_api_callback( $country_code = "" ){
	$validateData = array(
		'success'	=> false,
		'country_code'	=>	'',
		'standard_rate'	=>	null,
	);
	$euvatapi_access_key = ( !empty( get_option('euvatapi_access_key') ) ) ? get_option('euvatapi_access_key') : '9d5cb137a12069fb87aada7a82dc21a3';
	if( !empty( $country_code ) ){
		$endpoint = add_query_arg( array(
			'access_key' => $euvatapi_access_key,
			'country_code' => $country_code,
		), 'https://euvatapi.com/api/v1/rate' );
		$error_msg = "";
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $endpoint);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 30);
		$response = curl_exec($curl);
		if (curl_errno($curl)) {
			$error_msg = curl_error($curl);
		}
		$responseData = json_decode($response, true);
		curl_close($curl);
		if( empty( $error_msg ) ){
			if( $responseData['success'] == true ){
				$validateData['success'] = true;
				$validateData['country_code'] = $responseData['country_code'];
				$validateData['standard_rate'] = $responseData['standard_rate'];
			}
		}
	}
	return $validateData;
}
function cip_get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP'])){
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    }else if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }else if(isset($_SERVER['HTTP_X_FORWARDED'])){
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    }else if(isset($_SERVER['HTTP_FORWARDED_FOR'])){
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    }else if(isset($_SERVER['HTTP_FORWARDED'])){
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    }else if(isset($_SERVER['REMOTE_ADDR'])){
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    }else{
        $ipaddress = '';
	}
    return $ipaddress;
}
function isEU($countrycode) {
    $eu_countrycodes = array( 'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'EL', 'ES', 'FI', 'FR', 'GR', 'HR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK' );
    return (in_array($countrycode, $eu_countrycodes));
}
add_filter( 'gform_replace_merge_tags', 'cip_custom_merge_tags_replace_cb', 10, 7 );
function cip_custom_merge_tags_replace_cb( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
	global $wpdb;
	$buyer_email = $_SESSION['refAccount'];
	// $introducedby = "";
	$introducedby = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '';
	$business_name = "";
	$vat_number = "";
	$country = "";
	$invoiceTable = $wpdb->prefix.'cip_member_invoice';
	if( !empty( $_SESSION['refAccount'] ) ){
		$refAccount = $_SESSION['refAccount'];
		$getMemberData = $wpdb->get_row("SELECT * FROM $invoiceTable WHERE Email='$refAccount' ORDER BY `id` DESC");
		if( $getMemberData ){
			$buyer_email = $getMemberData->Email;
			// $introducedby = get_sponsor_username_byemail( $getMemberData->Email );
			$business_name = $getMemberData->BusinessName;
			$vat_number = $getMemberData->VatNumber;
			$country = $getMemberData->VATCountry;
		}
	}
	$custom_merge_tags = array(
		'{site_url}'  			=> get_site_url(),
		'{site_name}' 			=> get_bloginfo( 'name' ),
		'{cip_buyer_email}' 	=> $buyer_email,
		'{cip_introducedby}' 	=> $introducedby,
		'{cip_business_name}'	=> $business_name,
		'{cip_vat_number}'		=> $vat_number,
		'{cip_vat_country}'		=> $country,
	);
    return str_replace( array_keys( $custom_merge_tags ), array_values( $custom_merge_tags ), $text);
}
//for default value add custom merge tags
add_filter('gform_custom_merge_tags', 'cip_121021_custom_merge_tags', 10, 4);
function cip_121021_custom_merge_tags( $merge_tags, $form_id, $fields, $element_id ){
	$merge_tags[] = array('label' => 'CIP Buyer Email', 'tag' => '{cip_buyer_email}');
	$merge_tags[] = array('label' => 'CIP IntroducedBy', 'tag' => '{cip_introducedby}');
	$merge_tags[] = array('label' => 'CIP Business Name', 'tag' => '{cip_business_name}');
	$merge_tags[] = array('label' => 'CIP VAT Number', 'tag' => '{cip_vat_number}');
	$merge_tags[] = array('label' => 'CIP Country', 'tag' => '{cip_vat_country}');
	return $merge_tags;
}
add_filter('gform_field_content', 'cip_121021_field_content_replacebyvalue_cb', 999, 5);
function cip_121021_field_content_replacebyvalue_cb($field_content, $field, $value, $lead_id, $form_id) {
	global $wpdb;
	$buyer_email = $_SESSION['refAccount'];
	// $introducedby = "";
	$introducedby = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '';
	$business_name = "";
	$vat_number = "";
	$country = "";
	$invoiceTable = $wpdb->prefix.'cip_member_invoice';
	if( !empty( $_SESSION['refAccount'] ) ){
		$refAccount = $_SESSION['refAccount'];
		$getMemberData = $wpdb->get_row("SELECT * FROM $invoiceTable WHERE Email='$refAccount' ORDER BY `id` DESC");
		if( $getMemberData ){
			$buyer_email = $getMemberData->Email;
			// $introducedby = get_sponsor_username_byemail( $getMemberData->Email );
			$business_name = $getMemberData->BusinessName;
			$vat_number = $getMemberData->VatNumber;
			$country = $getMemberData->VATCountry;
		}
	}
    if (strpos($field_content, '{cip_buyer_email}') !== false) {
        $field_content = str_replace('{cip_buyer_email}', $buyer_email, $field_content);
    }
	if (strpos($field_content, '{cip_introducedby}') !== false) {
        $field_content = str_replace('{cip_introducedby}', $introducedby, $field_content);
    }
	if (strpos($field_content, '{cip_business_name}') !== false) {
        $field_content = str_replace('{cip_business_name}', $business_name, $field_content);
    }
	if (strpos($field_content, '{cip_vat_number}') !== false) {
        $field_content = str_replace('{cip_vat_number}', $vat_number, $field_content);
    }
	if (strpos($field_content, '{cip_vat_country}') !== false) {
        $field_content = str_replace('{cip_vat_country}', $country, $field_content);
    }
    return $field_content;
}
/* add_action('wp_footer','cip_introby_save_session');
function cip_introby_save_session(){
	if( isset( $_POST['gform_target_page_number_4'] ) && $_POST['gform_target_page_number_4'] == 3 ){
		$_SESSION['input_30_intro'] = $_POST['input_30'];
	}
} */
add_action('gform_after_submission_4', 'endo_add_entry_to_db', 10, 2);
function endo_add_entry_to_db($entry, $form) {

	// $entry_30_val = ( empty( $entry[30] ) ) ? $_SESSION['input_30_intro'] : $entry[30];

	  $business       = 	$entry[2];
	  $val            = 	$entry[15];
	  $price          = 	$entry[16];
	  $street_address = 	$entry['5.1'];
	  $address2       = 	$entry['5.2'];
	  $city           = 	$entry['5.3'];
	  $state          = 	$entry['5.4'];
	  $zip            = 	$entry['5.5'];
	  $country        =     $entry['5.6'];
	  $employees      = 	$entry[17];
	  $intro_by       =     $entry[30];
	  // $intro_by       =     $entry_30_val;
	  // $intro_by       =     $entry[35];
	  $email          = 	$entry[3];
	  $fname          = 	$entry['1.3'];
	  $lname          = 	$entry['1.6'];
	  $number         = 	$entry[4];
	  $weight         = 	$entry[11];
	  $category       = 	$entry[6];
	  $discount       = 	$entry[14];
	  $footprint      = 	$entry[13];
	  $vat            =     $entry[33];
	  $kilo           =      $entry[18];
	  $website        =   $entry[24];
	  $vat_country    =    $entry[20];
	  $amplivo_api_mode = get_option('amplivo_api_mode');
		if ($amplivo_api_mode == 'live') {
			$sourceUrl = get_option('amplivo_api_live_source_url') . 'get-csr-price-changes';
		} else {
			$sourceUrl = get_option('amplivo_api_test_source_url') . 'get-csr-price-changes';
		}
		// $sourceUrl = 'https://cloudhorizon.sandbox.jox.hu/api/get-csr-price-changes';

		// Prepare the request arguments for wp_remote_post()
		$username = get_option( 'amplivo_api_auth_username' );
		$auth_password = get_option( 'amplivo_api_auth_pwd' );

		// $username = 'amplivoapiuser';
		// $auth_password = 'fdlkg948ty89gh498rghuv';

		// Create an array with the request arguments, including Basic Auth in the headers
		$request_args = array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( $username . ':' . $auth_password ),
				'Content-Type' => 'application/json', // Adjust content type if necessary
			)
		);

		// Make the POST request using wp_remote_post()
		$responseApi = wp_remote_post($sourceUrl, $request_args);
		$response_body = wp_remote_retrieve_body( $responseApi );
		$data = json_decode( $response_body );

		$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
		if($hall_of_fame_price_type == 'csr'){
			$apiSellingPrice = ( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
			if(isset($data->result[0]))
			{
				if($data->result[0]->status == 'active')
				{
					$apiSellingPrice = $data->result[0]->csr_price;
				}
				else
				{
					foreach ($data->result as $key => $value) {
						if($value->status == 'active')
						{
							$apiSellingPrice = $value->csr_price;
						}
					}
				}
			}
		}else{
			$apiSellingPrice = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
		}
		
		$selling_price_csr = $apiSellingPrice;
	  $inclusiveUnit = 	$selling_price_csr;
	//   $inclusiveUnit = 	( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
	//   $inclusiveUnit = 	( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;

  	global $table_prefix,$wpdb;
	$invoiceTable=$table_prefix . 'cip_member_invoice';
	$account= $table_prefix.'sm_accounts_management';
	$invoice_record = "SELECT * FROM $invoiceTable ORDER BY `id` DESC";
	$invoice_result = $wpdb->get_row($invoice_record);
   //	$invoice_result = $wpdb->get_results($invoice_record);
	if( $invoice_result && !empty( $invoice_result->ProformaInvoiceNumber ) ){
		$proformaNo = $invoice_result->ProformaInvoiceNumber + 1;
	}else{
		$proformaNo = 1001;
	}
	/*$account_email = "SELECT * FROM $invoiceTable WHERE Email='$email'";
	$account_emailresult = $wpdb->get_row($account_email);
	$account_bank_id = $account_emailresult->BankId;*/

	//bank account assigning
	$bank_id = null;
	$LatestId = 0;
	$is_rotate = false;
	$getAssignedBank = $wpdb->get_row("SELECT * FROM $invoiceTable WHERE Email = '$email' ORDER BY id DESC");
	if( $getAssignedBank ){ //get from already assigned
		$checkActiveBank = $wpdb->get_row(" SELECT * FROM $account WHERE id = $getAssignedBank->BankId AND Status = 'Active' ");
		if( $checkActiveBank ){
			$bank_id = $checkActiveBank->id;
		}else{
			$getAssignedBanks = $wpdb->get_results("SELECT * FROM $invoiceTable WHERE Email = '$email'");
			$inIds = array();
			if( $getAssignedBanks ){
				foreach( $getAssignedBanks as $assignedBankData ){
					$inIds[] = $assignedBankData->BankId;
				}
			}
			if( !empty( $inIds ) ){
				$inIdsString = implode(",",$inIds);
				$getActiveBank = $wpdb->get_row(" SELECT * FROM $account WHERE id IN($inIdsString) AND Status = 'Active' ORDER BY id DESC ");
				if( $getActiveBank ){
					$bank_id = $getActiveBank->id;
				}else{ //get rotation
					$lastAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE LatestId = 1");
					if( $lastAssignedBank ){
						$LatestId = $lastAssignedBank->id;
						$getNextBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' AND id > $lastAssignedBank->id ORDER BY id ASC");
						if( $getNextBank ){
							$bank_id = $getNextBank->id;
							$is_rotate = true;
						}else{
							$firstAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' ORDER BY id ASC");
							if( $firstAssignedBank ){
								$bank_id = $firstAssignedBank->id;
								$is_rotate = true;
							}
						}
					}else{
						$firstAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' ORDER BY id ASC");
						if( $firstAssignedBank ){
							$bank_id = $firstAssignedBank->id;
							$is_rotate = true;
						}
					}
				}
			}
		}

	}else{ //get rotating
		$lastAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE LatestId = 1");
		if( $lastAssignedBank ){
			$LatestId = $lastAssignedBank->id;
			$getNextBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' AND id > $lastAssignedBank->id ORDER BY id ASC");
			if( $getNextBank ){
				$bank_id = $getNextBank->id;
				$is_rotate = true;
			}else{
				$firstAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' ORDER BY id ASC");
				if( $firstAssignedBank ){
					$bank_id = $firstAssignedBank->id;
					$is_rotate = true;
				}
			}
		}else{
			$firstAssignedBank = $wpdb->get_row("SELECT * FROM $account WHERE Status = 'Active' ORDER BY id ASC");
			if( $firstAssignedBank ){
				$bank_id = $firstAssignedBank->id;
				$is_rotate = true;
			}
		}
	}

	$vat_rate = null;
	$POVATPercentage = null;
	$VATPercentage = null;
	$countryCode = GF_Fields::get( 'address' )->get_country_code( $country );
	if( !empty( $vat ) && $countryCode == 'EE' ){
		$vat_rate = 22;
	}else if( !empty( $vat ) && isEU( $countryCode ) ){
		$vat_rate = 0;
		$POVATPercentage = "Reverse-Charge";
		$VATPercentage = "Reverse-Charge";
	}else if( !empty( $vat ) && $countryCode == 'GB' ){
		$vat_rate = 0;
	}else if( empty( $vat ) ){
		$euvatapi_ip_address = ( !empty( get_option('euvatapi_ip_address') ) ) ? get_option('euvatapi_ip_address') : '';
		if( !empty( $euvatapi_ip_address ) ){
			$ip_address = $euvatapi_ip_address;
		}else{
			$ip_address = cip_get_client_ip();
		}
		// $vatRateResponse = get_vat_rate_ipaddress_api_callback( $ip_address );
		$vatRateCountryResponse = get_vat_rate_code_api_callback( $countryCode );

		if( $vatRateCountryResponse['success'] ){
            $vat_rate = $vatRateCountryResponse['standard_rate'];
            $responseCountry = $vatRateCountryResponse['country_code'];
			if( $responseCountry == 'EE' ){
				$vat_rate = 22;
			}else if( $responseCountry == 'GB' ){
				$vat_rate = 0;
			}
		}
	}

	$formData = get_all_gform_fields_value( $form, $entry );
	$formData['type']	= 'vat_rate';
	$formData['ip_address']	= cip_get_client_ip();
	global $wpdb;
	$tableLog = $wpdb->prefix.'cip_logs';
	$logData = array(
		'user_id'	=>	0,
		'user_type'	=>	'buyer',
		'log_type'	=>	'api_track',
		'logs'		=>	maybe_serialize( $formData ),
		'_date'		=>	date_i18n('Y-m-d H:i:s'),
	);
	$log_insert = $wpdb->insert( $tableLog, $logData );
	/* if( !empty( $vat ) && $countryCode == 'EE' ){
		$vat_rate = 20;
	}else if( !empty( $vat ) && isEU( $countryCode ) ){
		$vat_rate = 0;
		$POVATPercentage = "Reverse-Charge";
		$VATPercentage = "Reverse-Charge";
	}else if( !empty( $vat ) && $countryCode == 'GB' ){
		// $vat_rate = 20;
		$vat_rate = 0;
	}else if( empty( $vat ) ){
		$euvatapi_ip_address = ( !empty( get_option('euvatapi_ip_address') ) ) ? get_option('euvatapi_ip_address') : '';
		if( !empty( $euvatapi_ip_address ) ){
			$ip_address = $euvatapi_ip_address;
		}else{
			$ip_address = cip_get_client_ip();
		}
		$vatRateResponse = get_vat_rate_ipaddress_api_callback( $ip_address );
		// $vatRateResponse = get_vat_rate_ipaddress_api_callback( '213.206.102.102' );
		if( $vatRateResponse['success'] ){
            $vat_rate = $vatRateResponse['standard_rate'];
            $vat_country = $vatRateResponse['country_code'];
			if( $vat_country == 'EE' ){
				$vat_rate = 20;
			}else if( $vat_country == 'GB' ){
				// $vat_rate = 20;
				$vat_rate = 0;
			}
		}
	} */
	if( is_null( $POVATPercentage ) ){
		$POVATPercentage = $vat_rate;
	}
	if( is_null( $VATPercentage ) ){
		$VATPercentage = $vat_rate;
	}
	/* if( $POVATPercentage == 'Reverse-Charge' ){
		$vat_rate = 0;
	} */

	$NetAmount = $price + ( ( $price * $vat_rate ) / 100 );
	$VATAmount = $NetAmount - $price;

    $entryDate= date_i18n( 'd-m-Y');
	//Current Timestamp
	$date = new DateTime();
	$curr_timestamp = $date->getTimestamp();
	$body = ['email'	=>	$email];
	$response = amplivo_api_send_requests( $body, 'get-user-data');
	if( $response['success'] == true ){
		$result = $response['result'];
		$Username = $result['Username'];
	}else{
		$Username = 'CSRCorpBuyer'.$proformaNo;
		$checkuserexistbody = ['username'	=>	$Username];
		$checkuserexistresponse = amplivo_api_send_requests( $checkuserexistbody, 'get-user-data');
		if( $checkuserexistresponse['success'] == true ){
			$suffix = 1;
			$baseUsername = 'CSRCorpBuyer' . $proformaNo;
			$baseEmail = 'csrcorpbuyer+' . $proformaNo;
			do {
				$Username = $baseUsername . str_pad($suffix, 2, '0', STR_PAD_LEFT);
				$checkuserexistbody = ['username' => $Username];
				$checkuserexistresponse = amplivo_api_send_requests($checkuserexistbody, 'get-user-data');
				$suffix++;
			} while ($checkuserexistresponse['success'] == true);
		}
	}
  	// add form data to custom database table
	$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
	$add_product = $wpdb->insert( $invoiceTable,
	    array(
 	      'BusinessName'       		=> 	$business,
		  'BusinessCategory'       	=> 	$category,
		  'Package'            		=> 	$val,
		  'ProductPrice'          	=> 	$price,
		  'Address1' 				=> 	$street_address,
		  'Address2'       			=> 	$address2,
		  'City'           			=> 	$city,
		  'State'          			=> 	$state,
		  'Country'        			=>  $country,
		  'Zipcode'            		=> 	$zip,
		  'Employees'      			=> 	$employees,
		  'IntroducedBy'  			=>  $intro_by,
		  'FirstName'          		=> 	$fname,
		  'LastName'          		=> 	$lname,
		  'Number'         			=> 	$number,
		  'Username'  				=>  $Username,
		  'Email'      				=> 	$email,
		  'CSRExchangeDiscount'     => 	$discount,
		  'PlasticWaste'         	=> 	$weight,
		  'PlasticWasteFootprint'	=> 	$footprint,
		  'Date'   					=>	$entryDate,
		  'UniqueKey'    			=>	$curr_timestamp,
		  'Status'    				=> 'Un-Paid',
		  'VatNumber'  				=>  $vat,
		  'InvoiceNumber'			=> 	null,
		  'ProformaInvoiceNumber'	=> 	$proformaNo,
		  'Kgs' 					=> 	$kilo,
		  'POVATAmount'				=>	$VATAmount,
		  'PONetAmount' 			=> 	$NetAmount,
		  'POGrossAmount' 			=> 	$price,
		  'POVATPercentage' 		=> 	$POVATPercentage,
		  'VATAmount' 				=> 	$VATAmount,
		  'NetAmount' 				=> 	$NetAmount,
		  'GrossAmount' 			=> 	$price,
		  'VATPercentage' 			=> 	$VATPercentage,
		  'Website' 				=> 	$website,
		  'VATCountry' 				=> 	$vat_country,
		  'BankId' 					=> 	$bank_id,
		  'ArchiveStatus' 			=> 	'No',
		  'inclusiveUnit' 			=> 	$inclusiveUnit,
		  'token'					=> 	strtoupper($hall_of_fame_price_type)
	    )
	);
	if( $add_product ){
		if( $is_rotate ){
			if( $LatestId ){
				$update_account = $wpdb->update( $account, array( 'LatestId'   => 	'0', ), array( 'id' => $LatestId ) );
			}
			if( $bank_id ){
				$update_account = $wpdb->update( $account, array( 'LatestId'   => 	'1', ), array( 'id' => $bank_id ) );
			}
		}
		setcookie('buyproductsubmit', 'yes', time() + (86400 / 1440 ) * 15, "/");
		$redirect_url = get_permalink( get_page_by_title( 'Order' ) );
		$redirect_link_param = add_query_arg( 'key', $curr_timestamp, $redirect_url );
		?>
		<script>window.location.replace("<?php echo $redirect_link_param; ?>");</script>
		<?php
	}
}
add_action('wp_ajax_cip_sm_api_settings_act','cip_sm_api_settings_act_cb');
function cip_sm_api_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsmapisettingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		update_option( 'euvatapi_access_key', $_POST['euvatapi_access_key'] );
		update_option( 'euvatapi_ip_address', $_POST['euvatapi_ip_address'] );
		update_option( 'csr_wallet_api_mode', $_POST['csr_wallet_api_mode'] );

		$selling_price_csr = ( !empty( $_POST['selling_price_csr'] ) ) ? $_POST['selling_price_csr'] : 0.025;
		// update_option( 'selling_price_csr', $selling_price_csr );
		$selling_price_csr_inc = ( 10 / $selling_price_csr ) / 50;
		//$selling_price_csr_inc = number_format((float)$selling_price_csr_inc, 2, '.', '');
		// update_option( 'selling_price_csr_inc', $selling_price_csr_inc );
		/*update_option( 'csr_wallet_api_mode_test_tkn', $_POST['csr_wallet_api_mode_test_tkn'] );
		update_option( 'csr_wallet_api_mode_test_api', $_POST['csr_wallet_api_mode_test_api'] );
		update_option( 'csr_wallet_api_mode_live_tkn', $_POST['csr_wallet_api_mode_live_tkn'] );
		update_option( 'csr_wallet_api_mode_live_api', $_POST['csr_wallet_api_mode_live_api'] );*/
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_hall_of_fame_price_type_settings_act','cip_hall_of_fame_price_type_settings_act_cb');
function cip_hall_of_fame_price_type_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxhall_of_fame_price_typesettingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		update_option( 'hall_of_fame_price_type', $_POST['hall_of_fame_price_type'] );
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
function csr_to_two_decimal( $csr_amount = 0, $round = false ){
	$csr_amount = number_format((float)$csr_amount, 2, '.', '');
	if( $round ){
		$csr_amount = round( $csr_amount );
	}
	return $csr_amount;
}
add_action('wp_ajax_cip_sm_cse_wallet_settings_act','cip_sm_cse_wallet_settings_act_cb');
function cip_sm_cse_wallet_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_csrwallet_settingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){

		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');
		$valueData[] = sprintf( __('Mode : %s', CIP_TXTDOMAIN), $csr_wallet_api_mode );
		$valueData[] = sprintf( __('Test token : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_test_tkn') );
		$valueData[] = sprintf( __('Test API : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_test_api') );
		$valueData[] = sprintf( __('Live token : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_live_tkn') );
		$valueData[] = sprintf( __('Live API : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_live_api') );
		$valueData[] = sprintf( __('Retirement confirmation block : %s', CIP_TXTDOMAIN), get_option('csr_retirement_confirmation_block') );

		$valueData[] = sprintf( __('Retirement Banners Initial Delay : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_initial_delay') );
		$valueData[] = sprintf( __('Retirement Banners Interval : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_interval') );
		$valueData[] = sprintf( __('Retirement Banners Display time : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_display_time') );

		update_option( 'csr_wallet_api_mode', $_POST['csr_wallet_api_mode'] );
		update_option( 'csr_wallet_api_mode_test_tkn', $_POST['csr_wallet_api_mode_test_tkn'] );
		update_option( 'csr_wallet_api_mode_test_api', $_POST['csr_wallet_api_mode_test_api'] );
		update_option( 'csr_wallet_api_mode_live_tkn', $_POST['csr_wallet_api_mode_live_tkn'] );
		update_option( 'csr_wallet_api_mode_live_api', $_POST['csr_wallet_api_mode_live_api'] );
		update_option( 'csr_retirement_confirmation_block', $_POST['csr_retirement_confirmation_block'] );
		update_option( 'csr_retirement_banner_initial_delay', $_POST['csr_retirement_banner_initial_delay'] );
		update_option( 'csr_retirement_banner_interval', $_POST['csr_retirement_banner_interval'] );
		update_option( 'csr_retirement_banner_display_time', $_POST['csr_retirement_banner_display_time'] );

		$valueData[] = __('***Updated Values***');
		$csr_wallet_api_mode = ( !empty( $_POST['csr_wallet_api_mode'] ) ) ? $_POST['csr_wallet_api_mode'] : 'test';
		$valueData[] = sprintf( __('Mode : %s', CIP_TXTDOMAIN), $csr_wallet_api_mode );
		$valueData[] = sprintf( __('Test token : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_test_tkn'] );
		$valueData[] = sprintf( __('Test API : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_test_api'] );
		$valueData[] = sprintf( __('Live token : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_live_tkn'] );
		$valueData[] = sprintf( __('Live API : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_live_api'] );
		$valueData[] = sprintf( __('Retirement confirmation block : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_confirmation_block'] );

		$valueData[] = sprintf( __('Retirement Banners Initial Delay : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_initial_delay'] );
		$valueData[] = sprintf( __('Retirement Banners Interval : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_interval'] );
		$valueData[] = sprintf( __('Retirement Banners Display time : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_display_time'] );

		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a");
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL);
		fclose($file);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );

		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// tab wise page
add_action('wp_ajax_cip_sm_csr_api_setting_form_act','cip_sm_csr_api_setting_form_act_cb');
function cip_sm_csr_api_setting_form_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_API_settings_xCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		
		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');
		$valueData[] = sprintf( __('Mode : %s', CIP_TXTDOMAIN), $csr_wallet_api_mode );
		$valueData[] = sprintf( __('Test token : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_test_tkn') );
		$valueData[] = sprintf( __('Test API : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_test_api') );
		$valueData[] = sprintf( __('Live token : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_live_tkn') );
		$valueData[] = sprintf( __('Live API : %s', CIP_TXTDOMAIN), get_option('csr_wallet_api_mode_live_api') );
		
		update_option( 'csr_wallet_api_mode', $_POST['csr_wallet_api_mode'] );
		update_option( 'csr_wallet_api_mode_test_tkn', $_POST['csr_wallet_api_mode_test_tkn'] );
		update_option( 'csr_wallet_api_mode_test_api', $_POST['csr_wallet_api_mode_test_api'] );
		update_option( 'csr_wallet_api_mode_live_tkn', $_POST['csr_wallet_api_mode_live_tkn'] );
		update_option( 'csr_wallet_api_mode_live_api', $_POST['csr_wallet_api_mode_live_api'] );
		
		$valueData[] = __('***Updated Values***');
		$csr_wallet_api_mode = ( !empty( $_POST['csr_wallet_api_mode'] ) ) ? $_POST['csr_wallet_api_mode'] : 'test';
		$valueData[] = sprintf( __('Mode : %s', CIP_TXTDOMAIN), $csr_wallet_api_mode );
		$valueData[] = sprintf( __('Test token : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_test_tkn'] );
		$valueData[] = sprintf( __('Test API : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_test_api'] );
		$valueData[] = sprintf( __('Live token : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_live_tkn'] );
		$valueData[] = sprintf( __('Live API : %s', CIP_TXTDOMAIN), $_POST['csr_wallet_api_mode_live_api'] );
		
		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a"); 
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL); 
		fclose($file);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );
		
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sm_retirement_banners_settings_act','cip_sm_retirement_banners_settings_act_cb');
function cip_sm_retirement_banners_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_retirement_BANNERS_settings_xCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		
		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');
		
		$valueData[] = sprintf( __('Retirement Banners Initial Delay : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_initial_delay') );
		$valueData[] = sprintf( __('Retirement Banners Interval : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_interval') );
		$valueData[] = sprintf( __('Retirement Banners Display time : %s', CIP_TXTDOMAIN), get_option('csr_retirement_banner_display_time') );
		
		update_option( 'csr_retirement_banner_initial_delay', $_POST['csr_retirement_banner_initial_delay'] );
		update_option( 'csr_retirement_banner_interval', $_POST['csr_retirement_banner_interval'] );
		update_option( 'csr_retirement_banner_display_time', $_POST['csr_retirement_banner_display_time'] );
		
		$valueData[] = __('***Updated Values***');
		
		$valueData[] = sprintf( __('Retirement Banners Initial Delay : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_initial_delay'] );
		$valueData[] = sprintf( __('Retirement Banners Interval : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_interval'] );
		$valueData[] = sprintf( __('Retirement Banners Display time : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_banner_display_time'] );
		
		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a"); 
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL); 
		fclose($file);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );
		
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sm_retirement_settings_act','cip_sm_retirement_settings_act_cb');
function cip_sm_retirement_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_retirement_SETTINGS_xCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		
		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');
		$valueData[] = sprintf( __('Retirement confirmation block : %s', CIP_TXTDOMAIN), get_option('csr_retirement_confirmation_block') );
		$valueData[] = sprintf( __('Retirement CSR Address : %s', CIP_TXTDOMAIN), get_option('retirement_csr_address') );
		$valueData[] = sprintf( __('Retirement CSR25 Address : %s', CIP_TXTDOMAIN), get_option('retirement_csr25_address') );
		
		update_option( 'csr_retirement_confirmation_block', $_POST['csr_retirement_confirmation_block'] );

		update_option( 'retirement_csr_address', $_POST['retirement_csr_address'] );

		update_option( 'retirement_csr25_address', $_POST['retirement_csr25_address'] );

		
		$valueData[] = __('***Updated Values***');
		
		$valueData[] = sprintf( __('Retirement confirmation block : %s', CIP_TXTDOMAIN), $_POST['csr_retirement_confirmation_block'] );
		$valueData[] = sprintf( __('Retirement CSR Address : %s', CIP_TXTDOMAIN), $_POST['retirement_csr_address'] );
		$valueData[] = sprintf( __('Retirement CSR25 Address : %s', CIP_TXTDOMAIN), $_POST['retirement_csr25_address'] );
		
		
		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a"); 
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL); 
		fclose($file);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );
		
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}


//CSR 25 Wallet API Mode
add_action('wp_ajax_cip_sm_cse_wallet_settings_act_25','cip_sm_cse_wallet_settings_act_cb_25');
function cip_sm_cse_wallet_settings_act_cb_25(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_csrwallet_settingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){

		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		$csr25_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');
		$valueData[] = sprintf( __('Mode 25 : %s', CIP_TXTDOMAIN), $csr25_wallet_api_mode );
		$valueData[] = sprintf( __('Test token 25 : %s', CIP_TXTDOMAIN), get_option('csr25_wallet_api_mode_test_tkn') );
		$valueData[] = sprintf( __('Test API 25 : %s', CIP_TXTDOMAIN), get_option('csr25_wallet_api_mode_test_api') );
		$valueData[] = sprintf( __('Live token 25 : %s', CIP_TXTDOMAIN), get_option('csr25_wallet_api_mode_live_tkn') );
		$valueData[] = sprintf( __('Live API 25 : %s', CIP_TXTDOMAIN), get_option('csr25_wallet_api_mode_live_api') );

		update_option( 'csr25_wallet_api_mode', $_POST['csr25_wallet_api_mode'] );
		update_option( 'csr25_wallet_api_mode_test_tkn', $_POST['csr25_wallet_api_mode_test_tkn'] );
		update_option( 'csr25_wallet_api_mode_test_api', $_POST['csr25_wallet_api_mode_test_api'] );
		update_option( 'csr25_wallet_api_mode_live_tkn', $_POST['csr25_wallet_api_mode_live_tkn'] );
		update_option( 'csr25_wallet_api_mode_live_api', $_POST['csr25_wallet_api_mode_live_api'] );

		$valueData[] = __('***Updated Values***');
		$csr25_wallet_api_mode = ( !empty( $_POST['csr25_wallet_api_mode'] ) ) ? $_POST['csr25_wallet_api_mode'] : 'test';
		$valueData[] = sprintf( __('Mode 25 : %s', CIP_TXTDOMAIN), $csr25_wallet_api_mode );
		$valueData[] = sprintf( __('Test token 25 : %s', CIP_TXTDOMAIN), $_POST['csr25_wallet_api_mode_test_tkn'] );
		$valueData[] = sprintf( __('Test API 25 : %s', CIP_TXTDOMAIN), $_POST['csr25_wallet_api_mode_test_api'] );
		$valueData[] = sprintf( __('Live token 25 : %s', CIP_TXTDOMAIN), $_POST['csr25_wallet_api_mode_live_tkn'] );
		$valueData[] = sprintf( __('Live API 25 : %s', CIP_TXTDOMAIN), $_POST['csr25_wallet_api_mode_live_api'] );

		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a");
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL);
		fclose($file);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );

		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
// tab wise page end
function cip_get_ether_balance( $ethaddress = '', $tokenType = 'csr' ){
	$csr_amount = 0;
	$tokenType = strtolower( $tokenType );
	if( !empty( $ethaddress ) ){

		if( $tokenType == 'csr25' ){
			$csr25_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
			$contractaddress = ( $csr25_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');
			$apikey = ( $csr25_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_api') : get_option('csr25_wallet_api_mode_test_api');
			$endpoint = ( $csr25_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
		}else{
			$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
			$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
			$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_api') : get_option('csr_wallet_api_mode_test_api');
			$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
		}

		$etherscanUrl = add_query_arg( array(
			'module' 			=> 'account',
			'action' 			=> 'tokenbalance',
			'contractaddress'	=>	$contractaddress,
			'address'			=>	$ethaddress,
			'tag'				=>	'latest',
			'apikey'			=>	$apikey
		), $endpoint );

		$request = wp_remote_get( $etherscanUrl );
		if( is_wp_error( $request ) ) {
			return $csr_amount;
		}
		$body = wp_remote_retrieve_body( $request );
		$data = json_decode( $body, true );
		if( isset( $data['result'] ) ){
			$csr_amount = $data['result'];
			$converter = new Bezhanov\Ethereum\Converter();
			$value = $converter->fromWei( $csr_amount , 'ether');
			if( $value > 0 ){
				// $csr_amount = rtrim( $value, 0 );
				$csr_amount = $value;
			}
		}
	}
	return $csr_amount;
}
function cip_pdf_number_formater( $numVal = 0 ){
	return number_format((float)$numVal, 2, '.', '');
}
add_filter( 'gform_next_button_4', 'cip_warning_buy_popup_cb', 10, 2 );
function cip_warning_buy_popup_cb( $button, $form ) {
    $dom = new DOMDocument();
    $dom->loadHTML( $button );
    // $input = $dom->getElementById( 'gform_next_button_4_27' )->item(0);
    // $input = $dom->getElementById( 'gform_next_button_4_27' );
	$input = $dom->getElementsByTagName( 'input' )->item(0);
	$id = $input->getAttribute('id');
	if( $id == 'gform_next_button_4_35' ){
		$onclick = $input->getAttribute( 'onclick' );
		$onclickNew = "warning_buy_popup();";
		$input->setAttribute( 'onclick', $onclickNew );
		// $input->setAttribute( 'onfocus','warning_buy_popup();' );
		return $dom->saveHtml( $input );
	}else{
		return $button;
	}
}
add_action('wp_footer','sponser_validation_script_cb');
function sponser_validation_script_cb(){
?><script>
var $ = jQuery;
var block_config = { message: null,overlayCSS:{ backgroundColor: '#fff',opacity:0.8} };
var $form = $('#gform_page_4_2');
var focusOutCount = 0;
// jQuery(window).on('load', function() {
jQuery(document).ready(function(){
	jQuery(document).on('gform_post_render', function(event, form_id, current_page){
		if( form_id == 4 && current_page == 2 ){
			if( jQuery('.gform_body #input_4_3').length > 0 ){
				if( focusOutCount != 2 ){
					focusOutCount++;
					setTimeout( function(){ if( jQuery('.gform_body #input_4_3').val() != "" ){ jQuery('.gform_body #input_4_3').trigger('focusout'); } }, 1000);
					console.log('second');
					return;
				}
				if( jQuery('.gform_body #input_4_3').val() != "" ){
					focusOutCount++;
					jQuery('.gform_body #input_4_3').trigger('focusout');
					console.log('first');
				}
			}
			console.log( 'form_id', form_id );
			console.log( 'current_page', current_page );
		}
    });
});
jQuery(document).ready(async function(){
	var error_msg = 'The supplied Sponsor ID does not correspond with our records. Please contact the person who referred you to this site. <br/>Proceeding without or with an incorrect Sponsor ID will delay your order.';
	var buy_email_status = "";
	if( jQuery('.gform_body #input_4_3').length > 0 ){
		sponser_validate_by_email( $("#input_4_3") );
	}
	if( jQuery('.gform_body #input_4_30').length > 0 ){
		sponser_validate_by_username( $("#input_4_30") );
		if( $('#input_4_3').val() != "" && $('#input_4_30').val() != ""  ){
			$('#input_4_30').focus();
			$('#input_4_30').blur();
		}
	}
	function sponser_validate_by_email(field) {
		var next_button = field.parent().parent().parent().parent().next().find('.button').next('.button');
		field.on("focusout", function(){
			var email_address = field.val();
			if( email_address != "" ){
				var $form = $("#input_4_3").closest('div.gfield');
				$form.block( block_config );
				var sponsor_name = $('#input_4_30').val();
				var data = { 'action' : 'sponser_validator_byemail_act', 'email' : email_address};
				$.post(cipscript.ajax_url, data, function(response){
					var obj = JSON.parse( response );
					// var errorElem = $('#field_4_35');
					var errorElem = $('#field_4_30');
					$('body').find('.introduced_error').remove();
					buy_email_status = obj.status;

					if( obj.login_error != "" ){
					    Swal.fire({ type: 'error', title: obj.login_error, text: '',allowOutsideClick: true}).then(function(){ window.location.href = obj.loginlink });
					}

					if( obj.username != "" ){
						// $('#input_4_35').val( obj.sponsor_full_name );
						$('#input_4_30').val( obj.username );
						if( obj.username != "" ){ $('#input_4_30').attr('readonly',true); }
					}else if( obj.status == 'active' && obj.username == "" ){
						// $('#input_4_35').val( obj.sponsor_full_name );
						$('#input_4_30').val( obj.username );
						if( obj.username == "" ){ $('#input_4_30').attr('readonly',false); }
						$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">'+error_msg+'</div>').appendTo( errorElem );
						// $('#input_4_35').val('');
					}else if( obj.status == "notfound" ){
						// $('#input_4_35').val('');
						$('#input_4_30').val('');
						$('#input_4_30').attr('readonly',false);
					}else if( obj.status != "notfound" && obj.status != "active" ){
						$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">'+error_msg+'</div>').appendTo( errorElem );
						// $('#input_4_35').val('');
						$('#input_4_30').val('');
						$('#input_4_30').attr('readonly',false);
					}else if( obj.status != "active" && sponsor_name == "" ){
						$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">'+error_msg+'</div>').appendTo( errorElem );
						// $('#input_4_35').val('');
						$('#input_4_30').val('');
						$('#input_4_30').attr('readonly',false);
					}
					$form.unblock();
				});
			}
		});
	}
	function sponser_validate_by_username(field) {
		var next_button = field.closest('.gform_page').find('.gform_next_button');
		field.on("focusout", function(){
			next_button.css('pointer-events', 'none');
			var username = field.val();
			var inputEmail = $('#input_4_3').val();
			if( username != "" ){
				var data = { 'action' : 'sponser_validator_byusername_act', 'username' : username, 'email' : inputEmail };
				$('body').find('.introduced_error').remove();
				var $form = $("#input_4_30").closest('div.gfield');
				$form.block( block_config );
				$.post(cipscript.ajax_url, data, function(response){
					var obj = JSON.parse( response );
					//console.log( obj );
					// var errorElem = $('#field_4_35');
					var errorElem = $('#field_4_30');
					$('body').find('.introduced_error').remove();
					// buy_email_status = obj.status;

					if( obj.email_username != 'notfound' && obj.email_username != obj.username ){
						$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">The supplied sponsor and email not matched</div>').appendTo( errorElem );
						next_button.css('pointer-events', 'none');
					}else{
						if( obj.username != "" ){
							// $('#input_4_35').val( obj.sponsor_full_name );
							$('#input_4_30').val( obj.username );
							next_button.css('pointer-events', '');
							// $('#input_4_3').val( obj.email );
						}else if( obj.username == "" ){
							// $('#input_4_35').val( obj.sponsor_full_name );
							$('#input_4_30').val( obj.username );
							// $('#input_4_3').val( obj.email );
							$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">'+error_msg+'</div>').appendTo( errorElem );
							// $('#input_4_35').val('');
							next_button.css('pointer-events', '');
						}else if( obj.status == "notfound" ){
							// $('#input_4_35').val('');
							$('#input_4_30').val('');
							next_button.css('pointer-events', '');
						}else if( obj.status != "active" ){
							$('<div id="introduced_error" class="introduced_error gfield_description validation_message gfield_validation_message">'+error_msg+'</div>').appendTo( errorElem );
							// $('#input_4_35').val('');
							$('#input_4_30').val('');
							next_button.css('pointer-events', '');
						}
					}

					$form.unblock();
				});
			}else if( username == "" ){
				$('body').find('.introduced_error').remove();
				next_button.css('pointer-events', '');
				// $('#input_4_35').val('');
				$('#input_4_30').val('');
			}
		});
	}
});
</script><?php
}
add_action('wp_ajax_sponser_validator_byemail_act','cip_sponser_validator_byemail_act_cb');
add_action('wp_ajax_nopriv_sponser_validator_byemail_act','cip_sponser_validator_byemail_act_cb');
function cip_sponser_validator_byemail_act_cb(){
	$validateData = array(
		'status'	=> 'notfound',
		'email'	=>	'',
		'username'	=>	'',
		'sponsor_full_name'	=>	'',
		'login_error'   =>  '',
		'loginlink' =>  get_permalink( 1067 ),
	);
	if( !empty( $_POST['email'] ) ){
		$email = $_POST['email'];
		$request_url = add_query_arg( 'email', urlencode( $email ), 'https://amplivo.com/api/userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$validateData = array(
					'status'	=> $data->Status,
					'email'	=>	$data->Email,
					'username'	=>	$data->sponsor_username,
					'sponsor_full_name'	=>	$data->sponsor_full_name,
					'login_error'   =>  '',
					'loginlink' =>  get_permalink( 1067 ),
				);
			}else if( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ){
				$validateData['username'] = $_COOKIE['csr_introducer'];
			}else if( isset( $_COOKIE['users_typed_introducer'] ) && !empty( $_COOKIE['users_typed_introducer'] ) ){
				$validateData['username'] = $_COOKIE['users_typed_introducer'];
			}
		}

		if( !is_user_logged_in() ){
    		$userData = get_user_by( 'email', $email );
    		if( $userData instanceof WP_User ) {
    		    if( $userData ){
    		        if( $userData->user_email == $email ){
    		            $validateData['login_error'] = __('Email address already registered. Please login to continue', CIP_TXTDOMAIN);
    		            $validateData['loginlink'] = get_permalink( 1067 );
    		        }
    		    }
    		}
		}

	}
	echo wp_json_encode( $validateData );
	exit;
}
add_action('wp_ajax_sponser_validator_byusername_act','cip_sponser_validator_byusername_act_cb');
add_action('wp_ajax_nopriv_sponser_validator_byusername_act','cip_sponser_validator_byusername_act_cb');
function cip_sponser_validator_byusername_act_cb(){
	$validateData = array(
		'status'	=> 'notfound',
		'email'	=>	'',
		'email_username'	=>	'notfound',
		'username'	=>	'',
		'sponsor_full_name'	=>	'',
	);
	if( !empty( $_POST['username'] ) ){
		$username = $_POST['username'];
		$request_url = add_query_arg( 'username', urlencode( $username ), 'https://amplivo.com/api/userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$validateData = array(
					'status'	=> $data->Status,
					'email'	=>	$data->Email,
					'email_username'	=>	'notfound',
					'username'	=>	$data->Username,
					'sponsor_full_name'	=>	$data->user_full_name,
				);
				setcookie('users_typed_introducer', $data->Username , 0, "/");
			}
		}
	}
	if( !empty( $_POST['email'] ) ){
		$email = $_POST['email'];
		$request_url = add_query_arg( 'email', urlencode( $email ), 'https://amplivo.com/api/userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$validateData['email_username']	= $data->sponsor_username;
			}
		}
	}
	echo wp_json_encode( $validateData );
	exit;
}
function get_sponsor_fullname_byuser( $username = '' ){
	$validateData = array(
		'status'	=> '',
		'email'	=>	'',
		'username'	=>	'',
		'sponsor_full_name'	=>	'',
	);
	if( !empty( $username ) ){
		$request_url = add_query_arg( 'username', urlencode( $username ), 'https://amplivo.com/api/userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$validateData = array(
					'status'	=> $data->Status,
					'email'	=>	$data->Email,
					'username'	=>	$data->Username,
					'sponsor_full_name'	=>	$data->user_full_name,
				);
			}
		}
	}
	return $validateData;
}
function get_sponsor_username_byemail( $email = '' ){
	$username =	'';
	if( !empty( $email ) ){
		$request_url = add_query_arg( 'email', urlencode( $email ), 'https://amplivo.com/api/userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$username = $data->sponsor_username;
			}
		}
	}
	return $username;
}
add_action('wp_ajax_cip_save_csr_sa_action','cip_save_csr_sa_action_callback');
function cip_save_csr_sa_action_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$getMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id=" . $_POST['cipthid'] . "");
	if( $getMember && $getMember->amount_due > 0 ){
		$amount_due = $getMember->amount_due;
		$csr_amount_issued = $getMember->csr_amount_issued;
		$csr_amount_issued_update = $getMember->csr_amount_issued + $amount_due;
		$where_data = array('id'	=>	$_POST['cipthid']);
		$update_data = array('amount_due'	=>	0,'csr_amount_issued' => $csr_amount_issued_update);
		$updated = $wpdb->update($tableName, $update_data, $where_data);
		if( $updated ){
			$data = array(
				'reference'			=>	$getMember->reference,
				'eth_address'		=>	$getMember->eth_address,
				'email'				=>	$getMember->email,
				'saving_csr_amount'	=>	$amount_due,
				'date_saving'		=>	date_i18n('Y-m-d H:i:s'),
				'status'			=>	0,
			);
			$tableSaving = $wpdb->prefix.'cip_holder_saving';
			$insert = $wpdb->insert($tableSaving, $data);
			if( $insert ){
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_addsaving_plan','cip_addsaving_plan_callback');
function cip_addsaving_plan_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tablePlan = $wpdb->prefix.'saving_plans';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsmsavingplanaddxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$data = array(
			'plan_name'		=>	$_POST['plan_name'],
			'plan_periods'	=>	$_POST['locking_period'],
			'plan_interest'	=>	$_POST['plan_interest'],
		);
		$insert = $wpdb->insert($tablePlan, $data);
		if( $insert ){
			$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path( 'saving-plans' ) ) );
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_addsaving_plan_edit','cip_addsaving_plan_edit_callback');
function cip_addsaving_plan_edit_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tablePlan = $wpdb->prefix.'saving_plans';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsmsavingplaneditxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$getPlan = $wpdb->get_row("SELECT * FROM $tablePlan WHERE id=".$_POST['pid']."");
		if( $getPlan ){

			$data = array(
				'plan_name'		=>	$_POST['plan_name'],
				'plan_periods'	=>	$_POST['locking_period'],
				'plan_interest'	=>	$_POST['plan_interest'],
				'updated_at'	=>	date_i18n('Y-m-d H:i:s'),
			);
			$where = array('id'	=>	$getPlan->id);
			$update = $wpdb->update($tablePlan, $data, $where);
			if( $update ){
				$out = array( "error" => 0, 'msg' => __('Updated', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path('saving-plans') ) );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_get_useretheraddress','cip_get_useretheraddress_callback');
function cip_get_useretheraddress_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$getMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id=".$_POST['thiseth']."");
	if( $getMember ){
		$out = array( "error" => 0, 'thiseth' => strtolower($getMember->eth_address ),'msg' => __('Success', CIP_TXTDOMAIN) );
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_verify_check_sign','cip_verify_check_sign_callback');
function cip_verify_check_sign_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'eth_sign_validate';
	if( wp_verify_nonce( $_POST['_micro'],'_XyVerfySignatureyX_' ) ){
		$refAccount = ( isset( $_SESSION['refAccount'] ) && !empty( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '';
		if( !empty( $refAccount ) ){
			$getSignData = $wpdb->get_row("SELECT * FROM $tableName WHERE email = '".$refAccount."' AND eth_address = '".$_POST['thiseth']."' ");
			if( $getSignData ){
				$update = $wpdb->update( $tableName, ['_date' => date_i18n('Y-m-d H:i:s')], ['id' => $getSignData->id] );
				if( $update ){
					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
				}
			}else{
				$insert = $wpdb->insert( $tableName, ['email' => $refAccount, 'eth_address' => $_POST['thiseth'], 'verify_status' => 1, '_date' => date_i18n('Y-m-d H:i:s') ] );
				if( $insert ){
					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_get_address_message_act','cip_get_address_message_act_callback');
function cip_get_address_message_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	$current_user = wp_get_current_user();
	if( $current_user ){
		$out = array( "error" => 0, 'msg' => 'I '.$current_user->user_email.' confirm that I own the address: '.strtolower( $_POST['thiseth'] ) );
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_get_csr_address_message_act','cip_get_csr_address_message_act_callback');
function cip_get_csr_address_message_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$getMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id=".$_POST['thiseth']." AND email='".$refAccount."' LIMIT 1");
	$current_user = wp_get_current_user();
	if( $getMember ){
		if( $current_user && !empty( $refAccount ) ){
			$eth_address = strtolower( $getMember->eth_address );
			$out = array( "error" => 0, 'msg' => 'I '.$refAccount.' confirm that I own the address: '.$eth_address);
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action( 'wp_ajax_get_csraddress_act', 'cip_get_csraddress_act_callback' );
function cip_get_csraddress_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyGetEthAddressCSRyX_' ) ){

		$decrypted_thisToken_raw = base64_decode( $_POST['thisToken'] );
		$thiseth = preg_replace(sprintf('/%s/', md5( strtoupper( $_POST['thisTokenType'] ) ) ), '', $decrypted_thisToken_raw);
		if( $_POST['thiseth'] != $thiseth ){
			$out = array( "error" => 1, 'msg' => __('Authentication failed.', CIP_TXTDOMAIN) );
			echo wp_json_encode($out);
			exit;
		}

		$getCsrData = $wpdb->get_row("SELECT * FROM $tableName WHERE id=".$_POST['thiseth']." AND email = '".$refAccount."' LIMIT 1");
		$getCsrDataExists = $wpdb->get_row("SELECT * FROM $tableName WHERE eth_address = '". $getCsrData->eth_address ."' AND sign_verify = 1 AND email != '".$refAccount."' LIMIT 1");

		if( $getCsrDataExists ){
			$out = array( "error" => 1, 'msg' => __('The CSR Wallet address is already verified by another user. <br> Please contact support.', CIP_TXTDOMAIN) );
		}else{
			if( $getCsrData ){
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $getCsrData->eth_address, 'thisToken' => $_POST['thisToken'], 'thisTokenType' => $_POST['thisTokenType'] );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action( 'wp_ajax_get_csraddress_sign_act', 'get_csraddress_sign_act_callback' );
function get_csraddress_sign_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyGetEthAddressCSRyX_' ) ){
		$getCsrData = $wpdb->get_row("SELECT * FROM $tableName WHERE id=".$_POST['thiseth']." AND email = '".$refAccount."'");
		if( $getCsrData ){
			$tableSign = $wpdb->prefix.'eth_sign_validate';
			$getValidateSign = $wpdb->get_row("SELECT * FROM $tableSign WHERE email = '".$getCsrData->email."' AND eth_address = '".$getCsrData->eth_address."' AND verify_status = 1");
			if( $getValidateSign ){
				$csr_amount = cip_get_ether_balance( $getCsrData->eth_address );
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $getCsrData->eth_address, 'amount' => $csr_amount );
			}else{
				$out = array( "error" => 1, 'msg' => __('Verified account not found', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_verifysig_act','cip_verifysig_act_callback');
function cip_verifysig_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$current_user = wp_get_current_user();
	if( $current_user ){		
		if( current_user_can( 'member' ) ){
			$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '';
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['address'] ), $_POST['signature'], strtolower( $_POST['address'] ));
			if( $verified ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$getSignDatas = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND eth_address = '".$_POST['address']."' ");
				if( $getSignDatas ){
					foreach( $getSignDatas as $getSignData ){
						$update = $wpdb->update( $tableTokenHolder, ['sign_verify' => 1], ['id' => $getSignData->id] );
						if( $update ){
							$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
						}
					}
				}
			}else{
				$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
			}
		}else{
			

			$current_ip = cip_get_client_ip();
			$current_user = wp_get_current_user();
			$user_id = $current_user->ID;
			$valueData = array();
			$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
			$valueData[] = date_i18n('d/m/Y H:i:s');
			$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
			$valueData[] = __('***Old Values***');
			
			$csr_wallet_fund_receiver_address = ( !empty( get_option('csr_wallet_fund_receiver_address') ) ) ? get_option('csr_wallet_fund_receiver_address') : '';
			$valueData[] = sprintf( __('CSR Saving Wallet Fund Receiver Address : %s', CIP_TXTDOMAIN), $csr_wallet_fund_receiver_address );
			
			update_option( 'csr_wallet_fund_receiver_address', $_POST['address'] );
			
			$valueData[] = __('***Updated Values***');
			
			$valueData[] = sprintf( __('CSR Saving Wallet Fund Receiver Address : %s', CIP_TXTDOMAIN), $_POST['address'] );
			
			
			$message = implode( PHP_EOL, $valueData);
			$filename = 'cip_wallet_option.log';
			$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a"); 
			$message = implode( PHP_EOL, $valueData);
			fwrite($file, $message . PHP_EOL); 
			fclose($file);
			
			$logs = $message;
			create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );

			$out = array( "error" => 0, 'msg' => __('Saved', CIP_TXTDOMAIN) );
			
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_verifysig_retirement_act','cip_verifysig_retirement_act_callback');
function cip_verifysig_retirement_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$current_user = wp_get_current_user();
	if( $current_user ){
		$out = array( "error" => 0, 'msg' => __('Saved', CIP_TXTDOMAIN) );
		update_option( 'retirement_csr_address', $_POST['address'] );
	}
	echo wp_json_encode($out);
	exit;
}
// Address for the retirement of CSR 25
add_action('wp_ajax_cip_verifysig_retirement_act_25','cip_verifysig_retirement_act_25_callback');
function cip_verifysig_retirement_act_25_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;

	$current_user = wp_get_current_user();
	if( $current_user ){
		$out = array( "error" => 0, 'msg' => __('Saved', CIP_TXTDOMAIN) );
		update_option( 'retirement_csr25_address', $_POST['address'] );

		$log_msg_retirement = __($current_user->user_email .' updated address for the retirement of CSR 25',CIP_TXTDOMAIN);
		create_cip_logs_entery( $current_user->ID, 'setting_option', '','sm', $log_msg_retirement, true );


		//cip_create_logs($log_msg);
		/* $verified = verifySignature('I '.$current_user->user_email.' confirm that I own the address: '.strtolower( $_POST['address'] ), $_POST['signature'], strtolower( $_POST['address'] ));
		if( $verified ){
			$out = array( "error" => 0, 'msg' => __('Saved', CIP_TXTDOMAIN) );
			update_option( 'retirement_csr_address', $_POST['address'] );
		}else{
			$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
		} */
	}
	echo wp_json_encode($out);
	exit;
}
use Elliptic\EC;
use kornrunner\Keccak;
function pubKeyToAddress($pubkey) {
    return "0x" . substr(Keccak::hash(substr(hex2bin($pubkey->encode("hex")), 1), 256), 24);
}
function verifySignature($message, $signature, $address) {
    $msglen = strlen($message);
    $hash   = Keccak::hash("\x19Ethereum Signed Message:\n{$msglen}{$message}", 256);
    $sign   = ["r" => substr($signature, 2, 64),
               "s" => substr($signature, 66, 64)];
    $recid  = ord(hex2bin(substr($signature, 130, 2))) - 27;
    if ($recid != ($recid & 1))
        return false;
    $ec = new EC('secp256k1');
    $pubkey = $ec->recoverPubKey($hash, $sign, $recid);
    return $address == pubKeyToAddress($pubkey);
}
// add_action('wp_ajax_cip_getsaveplans_act','cip_getsaveplans_act_callback');
function cip_getsaveplans_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$getSavingPlans = $wpdb->get_results("SELECT * FROM $tableSavingPlan WHERE plan_status = 1");
	$getMemberData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['thiscid']." AND email='".$refAccount."' AND sign_verify = 1");
	$savingPlansArr = array();
	if( $getSavingPlans && empty( $getMemberData->saved_amount ) && $getMemberData->corp_approved == 'Issued' && (int)$getMemberData->csr_amount_issued > 0 ){
		$formHtml = '<form name="choosesaveplanmm_frm" id="choosesaveplanmm_frm" style="position: unset;margin: 0;">
		<h4>'.__('CSR Savings/Staking',CIP_TXTDOMAIN).'</h4>';
		$formHtml .= '<p class="saving_modifier_elem">'.sprintf( __('You are saving %s CSR',CIP_TXTDOMAIN), $getMemberData->csr_amount_issued ).'</p>';
		$formHtml .= '<div class="form-group"><label for="csr_save_plan">'.__('Choose you required saving period').'</label>
		<select name="csr_save_plan" id="csr_save_plan">';
		foreach( $getSavingPlans as $getSavingPlan ){
			$formHtml .= '<option value="'.$getSavingPlan->id.'">'.$getSavingPlan->plan_name.'</option>';
		}
		$formHtml .= '</select></div>';
		// $formHtml .= '<div class="form-check"><input type="checkbox" name="saveallconfirm" id="saveallconfirm" value="1" class="form-check-input" /><label class="form-check-label" for="saveallconfirm">'.__('Save All My CSR',CIP_TXTDOMAIN).'</label></div>';
		$formHtml .= '<input type="hidden" name="_micro" value="'.wp_create_nonce('_XyProcessOnPlanMmyX_').'" />';
		$formHtml .= '<input type="hidden" name="action" value="cip_process_mm_saving_plans" />';
		$formHtml .= '<input type="hidden" name="actionid" value="'.$_POST['thiscid'].'" />';
		$formHtml .= '<br/><button type="submit" class="btn btn-secondary">'. __("Confirm",CIP_TXTDOMAIN).'</button>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Cancel",CIP_TXTDOMAIN).'</button>
		<br><br><label>'.__('Note: Only distributed CSR can be saved/staked.',CIP_TXTDOMAIN).'</label>
		<label>'.__('If you choose to save CSR before it is distributed it will automatically enter into your saving plan when distributed.',CIP_TXTDOMAIN).'</label>
		<label>'.__('If you choose to save CSR that has already been distributed you will need to send your CSR to the saving vault address with MetaMask in the next step.',CIP_TXTDOMAIN).'</label>
		<p><span class="form_response"></span></p>';
		$formHtml .= '</form>';
		$out = array( "error" => 0, 'data' => $formHtml );
	}else if( $getSavingPlans && empty( $getMemberData->saved_amount ) && (int)$getMemberData->amount_due > 0 ){
		$formHtml = '<form name="choosesaveplan_frm" id="choosesaveplan_frm" style="position: unset;margin: 0;">
		<h4>'.__('CSR Savings/Staking',CIP_TXTDOMAIN).'</h4>';
		$formHtml .= '<p class="saving_modifier_elem">'.sprintf( __('You are saving %s CSR',CIP_TXTDOMAIN), $getMemberData->amount_due ).'</p>';
		$formHtml .= '<div class="form-group"><label for="csr_save_plan">'.__('Choose you required saving period').'</label>
		<select name="csr_save_plan" id="csr_save_plan">';
		foreach( $getSavingPlans as $getSavingPlan ){
			$formHtml .= '<option value="'.$getSavingPlan->id.'">'.$getSavingPlan->plan_name.'</option>';
		}
		$formHtml .= '</select></div>';
		$formHtml .= '<div class="form-check"><input type="checkbox" name="saveallconfirm" id="saveallconfirm" value="1" class="form-check-input" /><label class="form-check-label" for="saveallconfirm">'.__('Save ALL My CSR',CIP_TXTDOMAIN).'</label></div>';
		$formHtml .= '<input type="hidden" name="_micro" value="'.wp_create_nonce('_XyProcessOnPlanyX_').'" />';
		$formHtml .= '<input type="hidden" name="action" value="cip_process_saving_plans" />';
		$formHtml .= '<input type="hidden" name="actionid" value="'.$_POST['thiscid'].'" />';
		$formHtml .= '<br/><button type="submit" class="btn btn-secondary">'. __("Confirm",CIP_TXTDOMAIN).'</button>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Cancel",CIP_TXTDOMAIN).'</button>
		<br><br><label>'.__('Note: Only distributed CSR can be saved/staked.',CIP_TXTDOMAIN).'</label>
		<label>'.__('If you choose to save CSR before it is distributed it will automatically enter into your saving plan when distributed.',CIP_TXTDOMAIN).'</label>
		<label>'.__('If you choose to save CSR that has already been distributed you will need to send your CSR to the saving vault address with MetaMask in the next step.',CIP_TXTDOMAIN).'</label>
		<p><span class="form_response"></span></p>';
		$formHtml .= '</form>';
		$out = array( "error" => 0, 'data' => $formHtml );
	}
	echo wp_json_encode($out);
	exit;
}
/*add_action('wp_ajax_cip_getsaveplans_all_act','cip_getsaveplans_all_act_callback');
function cip_getsaveplans_all_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$getSavingPlans = $wpdb->get_results("SELECT * FROM $tableSavingPlan WHERE plan_status = 1");
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$getMemberData = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0");
	$savingPlansArr = array();
	$total_amount_due = 0;
	if( $getSavingPlans && $getMemberData ){
		foreach( $getMemberData as $getMember ){
			$total_amount_due += $getMember->amount_due;
		}
		$formHtml = '<form name="choosesaveplan_all_frm" id="choosesaveplan_all_frm" style="position: unset;margin: 0;">
		<h4>'.__('Saving Plan',CIP_TXTDOMAIN).'</h4>';
		$formHtml .= '<p>'.sprintf( __('You are saving %s CSR',CIP_TXTDOMAIN), $total_amount_due ).'</p>';
		$formHtml .= '<label>'.__('Choose plan for saving').'</label>
		<select name="csr_save_plan" id="csr_save_plan">';
		foreach( $getSavingPlans as $getSavingPlan ){
			$formHtml .= '<option value="'.$getSavingPlan->id.'">'.$getSavingPlan->plan_name.'</option>';
		}
		$formHtml .= '</select>';
		$formHtml .= '<input type="hidden" name="_micro" value="'.wp_create_nonce('_XyAllProcessOnPlanAllyX_').'" />';
		$formHtml .= '<input type="hidden" name="action" value="cip_process_all_saving_plans" />';
		$formHtml .= '<br/><button type="submit" class="btn btn-secondary">'. __("Confirm",CIP_TXTDOMAIN).'</button>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Cancel",CIP_TXTDOMAIN).'</button>
		<p><span class="form_response"></span></p>';
		$formHtml .= '</form>';
		$out = array( "error" => 0, 'data' => $formHtml );
	}
	echo wp_json_encode($out);
	exit;
}*/
/*add_action('wp_ajax_cip_getsaveplans_unissued_all_act','cip_getsaveplans_unissued_all_act_callback');
function cip_getsaveplans_unissued_all_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$getSavingPlans = $wpdb->get_results("SELECT * FROM $tableSavingPlan WHERE plan_status = 1");
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$getMemberData = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
	$savingPlansArr = array();
	$total_amount_due = 0;
	if( $getSavingPlans && $getMemberData ){
		foreach( $getMemberData as $getMember ){
			$total_amount_due += $getMember->amount_due;
		}
		$formHtml = '<form name="choosesaveplan_all_frm" id="choosesaveplan_all_frm" style="position: unset;margin: 0;">
		<h4>'.__('Saving Plan',CIP_TXTDOMAIN).'</h4>';
		$formHtml .= '<p>'.sprintf( __('You are saving %s CSR',CIP_TXTDOMAIN), $total_amount_due ).'</p>';
		$formHtml .= '<div class="form-group"><label for="csr_save_plan">'.__('Choose plan for saving').'</label>
		<select name="csr_save_plan" id="csr_save_plan" class="form-control">';
		foreach( $getSavingPlans as $getSavingPlan ){
			$formHtml .= '<option value="'.$getSavingPlan->id.'">'.$getSavingPlan->plan_name.'</option>';
		}
		$formHtml .= '</select></div>';
		$formHtml .= '<div class="form-check"><input type="checkbox" name="saveallconfirm" id="saveallconfirm" value="1" class="form-check-input" /><label class="form-check-label" for="saveallconfirm">'.__('Save All My CSR',CIP_TXTDOMAIN).'</label></div>';
		$formHtml .= '<input type="hidden" name="_micro" value="'.wp_create_nonce('_XyAllProcessOnUnissuedPlanAllyX_').'" />';
		$formHtml .= '<input type="hidden" name="action" value="cip_process_unissued_all_saving_plans" />';
		$formHtml .= '<br/><button type="submit" class="btn btn-secondary">'. __("Confirm",CIP_TXTDOMAIN).'</button>
		<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Cancel",CIP_TXTDOMAIN).'</button>
		<p><span class="form_response"></span></p>';
		$formHtml .= '</form>';
		$out = array( "error" => 0, 'data' => $formHtml );
	}
	echo wp_json_encode($out);
	exit;
}*/
add_action('wp_ajax_cip_get_all_save_csr_amount','cip_get_all_save_csr_amount_callback');
function cip_get_all_save_csr_amount_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$getMemberRow = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['thiseth']." AND email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
	$total_amount_due = 0;
	if( $getMemberRow ){
		if( $_POST['thistoggle'] == "true" ){
			$getMemberData = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
			if( $getMemberData ){
				foreach( $getMemberData as $getMember ){
					$total_amount_due += $getMember->amount_due;
				}
			}
		}else{
			$total_amount_due = $getMemberRow->amount_due;
		}
		if( $total_amount_due > 0 ){
			$txt = sprintf( __('You are saving %s CSR',CIP_TXTDOMAIN), $total_amount_due );
			$out = array( "error" => 0, 'msg' => __('Success',CIP_TXTDOMAIN),'data' => $txt );
		}
	}
	echo wp_json_encode($out);
	exit;
}
// add_action('wp_ajax_cip_process_saving_plans','cip_process_saving_plans_callback');
function cip_process_saving_plans_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyProcessOnPlanyX_' ) ){
		$getPlanData = $wpdb->get_row("SELECT * FROM $tableSavingPlan WHERE id=".$_POST['csr_save_plan']."");
		if( $getPlanData ){
			$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['actionid'] ." AND email = '".$refAccount."' AND sign_verify = 1");

			if( $_POST['saveallconfirm'] == 1 ){
				if( $getMember ){
					$getMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
					$total_saving_amount = 0;

					foreach( $getMembers as $getMember ){
						if( $getMember->amount_due > 0 && empty( $getMember->saved_amount ) ){

							$csr_amount_save = $getMember->amount_due;
							$amount_due = $getMember->amount_due;

							$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
							$state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

							$csr_amount_issued = $csr_amount_save;
							$where_data = array('id'	=> $getMember->id );
							$update_data = array(
								'saved_amount'		=> $csr_amount_save,
								'saving_date' 		=> date_i18n('d/m/Y'),
								'saving_interest'	=> $getPlanData->plan_interest,
								'saving_periods'	=> $getPlanData->plan_periods,
								'saving_state'		=> $state,
							);
							$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
							if( $updated ){
								$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
								$logs = sprintf( __('Saving of %s, reference: %s, eth_address: %s, saved_amount: %s, saving_interest: %s, saving_periods: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, $csr_amount_save, $getPlanData->plan_interest, $getPlanData->plan_periods, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
							}
						}
					}
				}
			}else{
				if( $getMember && $getMember->amount_due > 0 && empty( $getMember->saved_amount ) ){

					$csr_amount_save = $getMember->amount_due;
					$amount_due = $getMember->amount_due;
					if( $csr_amount_save < 0 ){
						$out = array( "error" => 1, 'msg' => __('Not have sufficient amount to save', CIP_TXTDOMAIN) );
						echo wp_json_encode($out);
						exit;
					}

					$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
					$state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

					$csr_amount_issued = $csr_amount_save;
					$where_data = array('id'	=>	$_POST['actionid']);
					$update_data = array(
						'saved_amount'		=> $csr_amount_save,
						'saving_date' 		=> date_i18n('d/m/Y'),
						'saving_interest'	=> $getPlanData->plan_interest,
						'saving_periods'	=> $getPlanData->plan_periods,
						'saving_state'		=> $state,
					);
					$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
					if( $updated ){
						$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );

						$logs = sprintf( __('Saving of %s, reference: %s, eth_address: %s, saved_amount: %s, saving_interest: %s, saving_periods: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, $csr_amount_save, $getPlanData->plan_interest, $getPlanData->plan_periods, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
					}
				}
			}


		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_process_mm_saving_plans','cip_process_mm_saving_plans_callback');
function cip_process_mm_saving_plans_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyProcessOnPlanMmyX_' ) ){
		$getPlanData = $wpdb->get_row("SELECT * FROM $tableSavingPlan WHERE id=".$_POST['csr_save_plan']."");
		if( $getPlanData ){
			$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['actionid'] ." AND email = '".$refAccount."' AND sign_verify = 1");

			if( $_POST['saveallconfirm'] == 1 ){
				if( $getMember ){
					$getMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
					$total_saving_amount = 0;

					foreach( $getMembers as $getMember ){
						if( $getMember->amount_due > 0 && empty( $getMember->saved_amount ) ){

							$csr_amount_save = $getMember->amount_due;
							$amount_due = $getMember->amount_due;

							$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
							$state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

							$csr_amount_issued = $csr_amount_save;
							$where_data = array('id'	=> $getMember->id );
							$update_data = array(
								'saved_amount'		=> $csr_amount_save,
								'saving_date' 		=> date_i18n('d/m/Y'),
								'saving_interest'	=> $getPlanData->plan_interest,
								'saving_periods'	=> $getPlanData->plan_periods,
								'saving_state'		=> $state,
							);
							$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
							if( $updated ){
								$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
								$logs = sprintf( __('Saving of %s, reference: %s, eth_address: %s, saved_amount: %s, saving_interest: %s, saving_periods: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, $csr_amount_save, $getPlanData->plan_interest, $getPlanData->plan_periods, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
							}
						}
					}
				}
			}else{
				if( $getMember && (int)$getMember->csr_amount_issued > 0 && empty( $getMember->saved_amount ) ){

					$csr_amount_save = (int)$getMember->csr_amount_issued;
					if( $csr_amount_save <= 0 ){
						$out = array( "error" => 1, 'msg' => __('Not have sufficient amount to save', CIP_TXTDOMAIN) );
						echo wp_json_encode($out);
						exit;
					}
					$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
					$csr_amount_issued = ( $csr_wallet_api_mode == 'live' ) ? $getMember->csr_amount_issued : $getMember->csr_amount_issued;

					$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
					$masteraddress = get_option('csr_wallet_fund_receiver_address');
					$data = [
						'actionid'		=>	$_POST['actionid'],
						'planid'		=>	$_POST['csr_save_plan'],
						'ethaddress'	=>	$getMember->eth_address,
						'csramount'		=>	$csr_amount_issued,
						'masteraddress'	=>	$masteraddress,
						'tokenaddress'	=>	$tokenaddress,
						'api_mode'		=>	$csr_wallet_api_mode,
					];
					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $data );
				}
			}


		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_mm_transaction_save','cip_mm_transaction_save_callback');
function cip_mm_transaction_save_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyMmSaveTransHashyX_' ) ){
		$getPlanData = $wpdb->get_row("SELECT * FROM $tableSavingPlan WHERE id=".$_POST['planid']."");
		if( $getPlanData ){

			$getMemberData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['actionid']." AND email='".$refAccount."' AND sign_verify = 1");
			if( $getMemberData && empty( $getMemberData->saved_amount ) && $getMemberData->corp_approved == 'Issued' && (int)$getMemberData->csr_amount_issued > 0 ){
				$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';

				$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
				$masteraddress = get_option('csr_wallet_fund_receiver_address');
				$saving_state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

				$update_data = array(
					'transhash' => $_POST['transHash'],
					'contract_address' => $_POST['tkaddress'],
					'receiver_address' => $_POST['to'],
					'saving_state' => $saving_state,
			 	);
				$where_data = array('id'	=>	$getMemberData->id);
				$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
				if( strtolower( $tokenaddress ) == strtolower( $_POST['tkaddress'] ) && strtolower( $masteraddress ) == strtolower( $_POST['to'] ) ){
					$update_savedata = array(
						'saved_amount'		=> $_POST['value'],
						'saving_date' 		=> date_i18n('d/m/Y'),
						'saving_start_date' => date_i18n('d/m/Y'),
						'saving_interest'	=> $getPlanData->plan_interest,
						'saving_periods'	=> $getPlanData->plan_periods,
					);
					$save_updated = $wpdb->update($tableTokenHolder, $update_savedata, $where_data);
					if( $save_updated ){
						$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );

						$logs = sprintf( __('Saving transaction of %s, reference: %s, eth_address: %s, saved_amount: %s, saving_interest: %s, saving_periods: %s at %s', CIP_TXTDOMAIN), $getMemberData->email, $getMemberData->reference, $getMemberData->eth_address, $_POST['value'], $getPlanData->plan_interest, $getPlanData->plan_periods, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
					}
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_cancelsaveplan_act','cip_cancelsaveplan_act_callback');
function cip_cancelsaveplan_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyUnSavePlanyX_' ) ){

		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id = ".$_POST['thiseth']." AND email = '".$refAccount."' AND ( saving_start_date IS NULL OR saving_start_date = '' ) AND sign_verify = 1");

		if( $getMember ){
			$where_data = array('id'	=>	$getMember->id);
			$update_data = array(
				'saved_amount'		=> NULL,
				'saving_date' 		=> NULL,
				'saving_interest'	=> NULL,
				'saving_periods'	=> NULL,
				'saving_state'		=> 0,
			);
			$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
			if( $updated ){
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
				$logs = sprintf( __('Saving cancel of %s, reference: %s, eth_address: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
			}
		}

	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_cancelsaveplan_all_act','cip_cancelsaveplan_all_act_callback');
function cip_cancelsaveplan_all_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyUnSaveAllPlanyX_' ) ){

		$getMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND ( saved_amount IS NOT NULL OR saved_amount != '' ) AND ( saving_start_date IS NULL OR saving_start_date = '' ) AND sign_verify = 1");

		if( $getMembers ){
			foreach( $getMembers as $getMember ){
				if( $getMember ){

					$where_data = array('id'	=>	$getMember->id);
					$update_data = array(
						'saved_amount'		=> NULL,
						'saving_date' 		=> NULL,
						'saving_interest'	=> NULL,
						'saving_periods'	=> NULL,
						'saving_state'		=> 0,
					);
					$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
					if( $updated ){
						$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );

						$logs = sprintf( __('Saving cancel of %s, reference: %s, eth_address: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
					}
				}
			}
		}

	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_sa_unverifyaddress_act','cip_sa_unverifyaddress_act_callback');
function cip_sa_unverifyaddress_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.1', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	if( wp_verify_nonce( $_POST['_micro'],'_XyUnVerifyEthX_' ) && current_user_can( 'supportagent' ) ){

		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['thiseth'] ." AND sign_verify = 1");
		if( $getMember ){

			$where_data = array('email'	=>	$getMember->email, 'eth_address' => $getMember->eth_address );
			$update_data = array(
				'sign_verify'	=> NULL,
			);
			$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
			if( $updated ){
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
			}
		}

	}
	echo wp_json_encode($out);
	exit;
}
// add_action('wp_ajax_cip_process_all_saving_plans','cip_process_all_saving_plans_callback');
// function cip_process_all_saving_plans_callback(){
// 	$out = array( "error" => 1, 'msg' => __('Something went wrong.1', CIP_TXTDOMAIN) );
// 	global $wpdb;
// 	$tableSavingPlan = $wpdb->prefix.'saving_plans';
// 	$tableTokenHolder = $wpdb->prefix.'token_holder';
// 	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
// 	if( wp_verify_nonce( $_POST['_micro'],'_XyAllProcessOnPlanAllyX_' ) ){
// 		$getPlanData = $wpdb->get_row("SELECT * FROM $tableSavingPlan WHERE id=".$_POST['csr_save_plan']."");
// 		if( $getPlanData ){
// 			$getMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0");
// 			$total_saving_amount = 0;
// 			if( $getMembers ){
// 				foreach( $getMembers as $getMember ){
// 					if( $getMember && $getMember->amount_due > 0 ){

// 						$where_data = array('id'	=>	$getMember->id);
// 						$update_data = array('amount_due' => 0,'saved_amount'	=>	$getMember->amount_due,'saved_date' => date_i18n('Y-m-d H:i:s'));
// 						$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
// 						if( $updated ){
// 							$total_saving_amount += $getMember->amount_due;
// 						}
// 					}
// 				}
// 			}
// 			if( $total_saving_amount > 0 ){
// 				$endDateObj = DateTime::createFromFormat('Y-m-d H:i:s', date_i18n('Y-m-d 00:00:01'));
// 				$endDate = $endDateObj->modify('+'.( $getPlanData->plan_periods - 1 ).' day')->format('Y-m-d H:i:s');
// 				$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
// 				$state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;
// 				$data = array(
// 					'reference'			=>	'save_all',
// 					'eth_address'		=>	'save_all',
// 					'email'				=>	$refAccount,
// 					'saving_csr_amount'	=>	$total_saving_amount,
// 					'date_saving'		=>	date_i18n('Y-m-d 00:00:01'),
// 					'end_date'			=>	$endDate,
// 					'update_at'			=>	date_i18n('Y-m-d H:i:s'),
// 					'interest'			=>	$getPlanData->plan_interest,
// 					'periods'			=>	$getPlanData->plan_periods,
// 					'interest_total'	=>	( $total_saving_amount * $getPlanData->plan_interest / 100 ) / $getPlanData->plan_periods,
// 					'state'				=>	$state,
// 					'status'			=>	1,
// 				);
// 				$tableSaving = $wpdb->prefix.'cip_holder_saving';
// 				$insert = $wpdb->insert($tableSaving, $data);
// 				if( $insert ){
// 					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
// 				}
// 			}
// 		}
// 	}
// 	echo wp_json_encode($out);
// 	exit;
// }
add_action('wp_ajax_cip_process_unissued_all_saving_plans','cip_process_unissued_all_saving_plans_callback');
function cip_process_unissued_all_saving_plans_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableSavingPlan = $wpdb->prefix.'saving_plans';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyAllProcessOnUnissuedPlanAllyX_' ) ){
		$getPlanData = $wpdb->get_row("SELECT * FROM $tableSavingPlan WHERE id=".$_POST['csr_save_plan']."");
		if( $getPlanData ){
			$getMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND amount_due > 0 AND ( saved_amount IS NULL OR saved_amount = '' ) AND sign_verify = 1");
			$total_saving_amount = 0;

			foreach( $getMembers as $getMember ){
				if( $getMember->amount_due > 0 && empty( $getMember->saved_amount ) ){

					$csr_amount_save = $getMember->amount_due;
					$amount_due = $getMember->amount_due;

					$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
					$state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

					$csr_amount_issued = $csr_amount_save;
					$where_data = array('id'	=> $getMember->id );
					$update_data = array(
						'saved_amount'		=> $csr_amount_save,
						'saving_date' 		=> date_i18n('d/m/Y'),
						'saving_interest'	=> $getPlanData->plan_interest,
						'saving_periods'	=> $getPlanData->plan_periods,
						'saving_state'		=> $state,
					);
					$updated = $wpdb->update($tableTokenHolder, $update_data, $where_data);
					if( $updated ){
						$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );

						$logs = sprintf( __('Unissued saving of %s, reference: %s, eth_address: %s, saved_amount: %s, saving_interest: %s, saving_periods: %s at %s', CIP_TXTDOMAIN), $getMember->email, $getMember->reference, $getMember->eth_address, $csr_amount_save, $getPlanData->plan_interest, $getPlanData->plan_periods, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'saving', '','member', $logs, true  );
					}
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action( 'wp_ajax_csr_retirement_process_act', 'cip_csr_retirement_process_act_callback' );
function cip_csr_retirement_process_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';

	$retirement_maintenance_mode = get_option('cip_retirement_maintenance_mode');
	if( $retirement_maintenance_mode ){
		$out = array( "error" => 1, 'msg' => __('CSR Retirement Process is Under Maintenance.<br>Please try again later.', CIP_TXTDOMAIN) );
		echo wp_json_encode($out);
		exit;
	}

	if( wp_verify_nonce( $_POST['_micro'],'_XyCsrRetirementProcessyX_' ) ){

		$decrypted_thisToken_raw = base64_decode( $_POST['thisToken'] );
		$thiseth = preg_replace(sprintf('/%s/', md5( strtoupper( $_POST['thisTokenType'] ) ) ), '', $decrypted_thisToken_raw);
		if( $_POST['thiseth'] != $thiseth ){
			$out = array( "error" => 1, 'msg' => __('Authentication failed.', CIP_TXTDOMAIN) );
			echo wp_json_encode($out);
			exit;
		}

		$getCsrData = $wpdb->get_row("SELECT * FROM $tableName WHERE id=".$_POST['thiseth']." AND sign_verify = 1 AND email = '".$refAccount."'");
		$getCsrDataExists = $wpdb->get_row("SELECT * FROM $tableName WHERE eth_address = '". $getCsrData->eth_address ."' AND email != '".$refAccount."' AND sign_verify = 1");
		if( $getCsrDataExists ){
			$out = array( "error" => 1, 'msg' => __('CSR wallet address in use by multiple CSRnow members<br/>You cannot retire from a CSR Wallet address used by more than one account.<br/>You will need to transfer your CSR to another wallet address and verify that address. We aim to provide a facility to update your CSR wallet address later this year after CSRCentral is live.', CIP_TXTDOMAIN) );
		}else{
			if( $getCsrData ){

				$eth_balance = cip_get_ether_balance( $getCsrData->eth_address, $_POST['thisTokenType'] );

				$formHtml = '<form name="get_retirement_amount_frm" id="get_retirement_amount_frm" style="position: unset;margin: 0;">
				<h4>'.__('CSR Plastic Credit Retirement',CIP_TXTDOMAIN).'</h4>';
				$formHtml .= '<p>'.__('By retiring your CSR Plastic Credits you will become the permanent registered end-user of your CSR Plastic Credit.',CIP_TXTDOMAIN).'</p>';
				$formHtml .= '<p>'.__('The retirement of CSR Plastic Credits cannot be reversed.',CIP_TXTDOMAIN).'</p>';
				$formHtml .= '<p>'.__('Retired CSR Plastic Credits are permanently locked in the CSR Retirement Vault from which withdrawal is not possible under any circumstances. You will forever be recognised as the end-user of the retired CSR Plastic Credits.',CIP_TXTDOMAIN).'</p>';

				$formHtml .= '<div class="form-group amount_grp_box"><span>'.__('I would like to retire:',CIP_TXTDOMAIN) .'</span><input type="number" name="retire_amount" data-max="'. floatval( $eth_balance ) .'" step="0.01" /><span>'. __('CSR',CIP_TXTDOMAIN).'</span>';
				$formHtml .= '</div>';
				if (fmod($eth_balance, 1) !== 0.0) {
					$formHtml .= '<div class="form-check max_section"><input type="checkbox" name="saveallretirement" id="saveallretirement" value="1" class="form-check-input" /><label class="form-check-label" for="saveallretirement">'. sprintf( __('Max (%s)',CIP_TXTDOMAIN), number_format( $eth_balance,2 ) ) .'</label></div>';
				}else{
					$formHtml .= '<div class="form-check max_section"><input type="checkbox" name="saveallretirement" id="saveallretirement" value="1" class="form-check-input" /><label class="form-check-label" for="saveallretirement">'. sprintf( __('Max (%s)',CIP_TXTDOMAIN), number_format( $eth_balance ) ) .'</label></div>';
				}
				$formHtml .= '<input type="hidden" name="_micro" value="'.wp_create_nonce('_XyProcessOnRetirementCsrX_').'" />';
				$formHtml .= '<input type="hidden" name="action" value="cip_process_retirement_csr" />';
				$formHtml .= '<input type="hidden" name="actionid" value="'.$_POST['thiseth'].'" />';
				$formHtml .= '<input type="hidden" name="thisToken" value="'.$_POST['thisToken'].'" />';
				$formHtml .= '<input type="hidden" name="thisTokenType" value="'.$_POST['thisTokenType'].'" />';

				// $formHtml .= '<p class="retire_amount_modifier_elem">'.sprintf( __('You are about to retire %s CSR.',CIP_TXTDOMAIN), '-' ).'</p>';
				/*$formHtml .= '<p class="retire_amount_modifier_elem"></p>';
				$formHtml .= '<p>'.sprintf( __('The retirement of CSR cannot be reversed and is a prominent record against the CSR Wallet address %s',CIP_TXTDOMAIN), $getCsrData->eth_address ).'</p>';
				$formHtml .= '<p>'.__('** Retired CSR is permanently locked in the CSR retirement vault from which withdrawal is not possible under any circumstances. You will forever be recognized as the end-user of the retired CSR.',CIP_TXTDOMAIN).'</p>';*/

				$formHtml .= '<br/><button type="submit" class="btn btn-secondary">'. __("Retire now",CIP_TXTDOMAIN).'</button>
				<span data-toggle-tt="tooltip" data-placement="top" title="After clicking Retire now you will be required to confirm the transaction with Metamask and pay the applicable gas fees on the Ethereum blockchain. We do not charge any fees for the retirement process, you only pay the applicable gas fees on the Ethereum blockchain." class="fa fa-info-circle"></span>
				<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Cancel",CIP_TXTDOMAIN).'</button>
				<br><p><span class="form_response"></span></p>';
				$formHtml .= '</form>';
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $formHtml );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_process_retirement_csr','cip_process_retirement_csr_callback');
function cip_process_retirement_csr_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';

	$retirement_maintenance_mode = get_option('cip_retirement_maintenance_mode');
	if( $retirement_maintenance_mode ){
		$out = array( "error" => 1, 'msg' => __('CSR Retirement Process is Under Maintenance.<br>Please try again later.', CIP_TXTDOMAIN) );
		echo wp_json_encode($out);
		exit;
	}

	if( wp_verify_nonce( $_POST['_micro'],'_XyProcessOnRetirementCsrX_' ) ){

		$decrypted_thisToken_raw = base64_decode( $_POST['thisToken'] );
		$actionid = preg_replace(sprintf('/%s/', md5( strtoupper( $_POST['thisTokenType'] ) ) ), '', $decrypted_thisToken_raw);
		if( $_POST['actionid'] != $actionid ){
			$out = array( "error" => 1, 'msg' => __('Authentication failed.', CIP_TXTDOMAIN) );
			echo wp_json_encode($out);
			exit;
		}

		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['actionid'] ." AND email = '".$refAccount."' AND sign_verify = 1");
		if( $getMember ){

			$thisTokenType = strtolower( $_POST['thisTokenType'] );
			if( $thisTokenType == 'csr25' ){
				$csr_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
				$csr_amount_issued = ( $csr_wallet_api_mode == 'live' ) ? $getMember->csr_amount_issued : $getMember->csr_amount_issued;

				$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');
				$masteraddress = get_option('retirement_csr25_address');
			}else{
				$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
				$csr_amount_issued = ( $csr_wallet_api_mode == 'live' ) ? $getMember->csr_amount_issued : $getMember->csr_amount_issued;

				$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
				$masteraddress = get_option('retirement_csr_address');
			}

			$eth_balance = cip_get_ether_balance( $getMember->eth_address, $thisTokenType );
			if( !is_numeric( $eth_balance ) || $eth_balance <= 0 ){
				$out = array( "error" => 1, 'msg' => sprintf( __('No CSR at blockchain address %s',CIP_TXTDOMAIN), $getMember->eth_address ) );
				echo wp_json_encode($out);
				exit;
			}
			if( $_POST['retire_amount'] > $eth_balance ){
				$out = array( "error" => 1, 'msg' => sprintf( __('Insufficient amount of CSR at blockchain address %s',CIP_TXTDOMAIN), $getMember->eth_address ) );
				echo wp_json_encode($out);
				exit;
			}

			$data = [
				'actionid'		=>	$_POST['actionid'],
				'ethaddress'	=>	$getMember->eth_address,
				'csramount'		=>	$_POST['retire_amount'],
				'masteraddress'	=>	$masteraddress,
				'tokenaddress'	=>	$tokenaddress,
				'api_mode'		=>	$csr_wallet_api_mode,
				'thisToken'		=>	$_POST['thisToken'],
				'thisTokenType'	=>	$_POST['thisTokenType']
			];
			$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $data );
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_mm_retirement_save','cip_mm_retirement_save_callback');
function cip_mm_retirement_save_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyMmSaveTransRetireyX_' ) ){
		$getMemberData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['actionid']." AND email='".$refAccount."' AND sign_verify = 1");
		if( $getMemberData ){

			$thisTokenType = strtolower( $_POST['thisTokenType'] );
			if( $thisTokenType == 'csr25' ){

				$csr_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
				$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');
				$masteraddress = get_option('retirement_csr25_address');

			}else{
				$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
				$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
				$masteraddress = get_option('retirement_csr_address');
			}

			$saving_state = ( $csr_wallet_api_mode == 'live' ) ? 1 : 0;

			$getRetirementTxns = $wpdb->get_row("SELECT * FROM $tableRetirement WHERE `retire_transhash` = '". $_POST['transHash'] ."'");
			if( $getRetirementTxns ){
				$out = array( "error" => 1, 'msg' => __('Duplicate transaction found. Please try again.', CIP_TXTDOMAIN) );
				echo wp_json_encode($out);
				exit;
			}

			if( strtolower( $tokenaddress ) == strtolower( $_POST['tkaddress'] ) && strtolower( $masteraddress ) == strtolower( $_POST['to'] ) ){

				$thisTokenType = strtoupper( $_POST['thisTokenType'] );
				$token = ( $thisTokenType == 'CSR' || $thisTokenType == 'CSR25' ) ? $thisTokenType : 'CSR' ;

				$data = array(
					'email'						=> $refAccount,
					'username'					=> $getMemberData->username,
					'first_name'				=> $getMemberData->first_name,
					'last_name'					=> $getMemberData->last_name,
					'eth_address'				=> $getMemberData->eth_address,
					'retire_amount'				=> 0,
					'retire_amount_log'			=> $_POST['value'],
					'retire_date' 				=> date_i18n('Y-m-d H:i:s'),
					'retire_confirm_date' 		=> null,
					'retire_state'				=> $saving_state,
					'retire_transhash' 			=> $_POST['transHash'],
					'retire_contract_address'	=> $_POST['tkaddress'],
					'retire_receiver_address'	=> $_POST['to'],
					'retire_status'				=> 0,
					'token'						=> $token
				);
				$insert = $wpdb->insert($tableRetirement, $data);
				if( $insert ){
					// $msg = "<p>".sprintf( __('Congratulations on your retirement of %s CSR Plastic Credits!',CIP_TXTDOMAIN), $_POST['value'] )."</p>";
					$msg = "<p style='font-weight: 600;'>".__('Congratulations on your retirement of CSR Plastic Credits!',CIP_TXTDOMAIN)."</p>";
					$msg .= "<p style='font-weight: 600;'>".__('We would like to take this opportunity to thank you for your contribution on becoming Plastic Neutral.',CIP_TXTDOMAIN)."</p>";
					$msg .= "<p style='font-weight: 600;'>".__('Your certificate will be available in few moments once the blockchain has processed the transaction.',CIP_TXTDOMAIN)."</p>";


					$logs = sprintf( __('Member: username: %s, email: %s, has initiated a retirement of %s CSR from CSR address: %s,

					Transaction Hash: %s', CIP_TXTDOMAIN), $getMemberData->username, $refAccount, $_POST['value'], $getMemberData->eth_address, $_POST['transHash'] );
					create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
					$out = array( "error" => 0, 'msg' => $msg );
				}else{
					$logs = sprintf( __('Error to save retire data : %s at %s', CIP_TXTDOMAIN), json_encode( $data ), date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
					$out = array( "error" => 1, 'msg' => __('Error to save retirement data') );
				}
			}

		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_mm_retirement_error_log','cip_mm_retirement_error_log_callback');
function cip_mm_retirement_error_log_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';

	$getMemberData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE 1 AND `email`='".$refAccount."'");

	$logs = sprintf( __('Error on Retirement of %s CSR for username: %s, email: %s, from address: %s. Error: %s at %s', CIP_TXTDOMAIN), $_POST['value'], $getMemberData->username, $getMemberData->email, $_POST['from'], $_POST['msg'], date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
	$out = array( "error" => 1, 'msg' => __('Retirement error log saved') );
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_confirmations_block_number_script','cip_confirmations_block_number_script_cb');
add_action('wp_ajax_nopriv_confirmations_block_number_script','cip_confirmations_block_number_script_cb');
function cip_confirmations_block_number_script_cb(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableRetirement = $wpdb->prefix.'retirement_data';
	if( isset( $_GET['cronmicro'] ) && str_rot13( $_REQUEST['cronmicro'] ) === 'CIPconfirmations_blockCIP'  ){ //PVCpbasvezngvbaf_oybpxPVC

		$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE retire_status = 0");
		if( $getRetirements ){
			foreach( $getRetirements as $getRetirement ){

				$thisTokenType = strtolower( $getRetirement->token );

				if( $thisTokenType == 'csr25' ){
					
					$csr_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
					$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');
					$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_api') : get_option('csr25_wallet_api_mode_test_api');
					$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
					$tokenSymbolVerify = ( $csr_wallet_api_mode == 'live' ) ? 'CSR25' : 'TESTCSR25';

				}else{
				
					$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
					$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
					$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_api') : get_option('csr_wallet_api_mode_test_api');
					$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
					$tokenSymbolVerify = ( $csr_wallet_api_mode == 'live' ) ? 'CSR' : 'TESTCSR';

				}

				if( !empty( $getRetirement->retire_transhash ) ){
					$txhash = $getRetirement->retire_transhash;
					$csr_retirement_confirmation_block = ( !empty( get_option('csr_retirement_confirmation_block') ) ) ? get_option('csr_retirement_confirmation_block') : 0 ;
					$getTxnUrl = add_query_arg( array(
						'module' => 'proxy',
						'action' => 'eth_getTransactionByHash',
						'txhash' => $txhash,
						'apikey'=>	$apikey
					), $endpoint );

					$request = wp_remote_get( $getTxnUrl, array( 'timeout'     => 15 ) );
					if( is_wp_error( $request ) ) {
						$out = array( "error" => 1, 'msg' => $request->get_error_message() );
						echo wp_json_encode($out);
						continue;
					}
					// echo "<pre>"; print_r( $request ); echo "</pre>";

					$body = wp_remote_retrieve_body( $request );
					$data = json_decode( $body, true );
					if( isset( $data['result'] ) ){
						$blockNumberHex = $data['result']['blockNumber'];
						$blockNumberDec = hexdec( $blockNumberHex );

						$getBlockUrl = add_query_arg( array(
							'module' => 'proxy',
							'action' => 'eth_blockNumber',
							'apikey'=>	$apikey
						), $endpoint );
						$blockRequest = wp_remote_get( $getBlockUrl, array( 'timeout'     => 15 ) );

						// echo "<pre>"; print_r( $blockRequest ); echo "</pre>";

						if( is_wp_error( $blockRequest ) ) {
							$out = array( "error" => 1, 'msg' => $blockRequest->get_error_message() );
							echo wp_json_encode($out);
							continue;
						}
						$blockBody = wp_remote_retrieve_body( $blockRequest );
						$blockData = json_decode( $blockBody, true );
						if( isset( $blockData['result'] ) ){
							$blockResult = hexdec( $blockData['result'] );
						}
						if( $blockNumberDec && $blockResult ){
							$confirmBlock = $blockResult - $blockNumberDec;
							if( $confirmBlock >= $csr_retirement_confirmation_block ){

								$ethResponseBlock = get_etherscan_transaction_by_block_response( $blockNumberDec, $getRetirement->eth_address, $txhash, $thisTokenType );

								// echo "<pre>"; print_r( $ethResponseBlock ); echo "</pre>";

								if( $ethResponseBlock['status'] && isset( $ethResponseBlock['result'][0] ) ){
									$resultData = $ethResponseBlock['result'][0];
									$converter = new Bezhanov\Ethereum\Converter();
									$responseAmount = $convertedValue = floatval( $converter->fromWei( (string)$resultData['value'] , 'ether') );
									if( strtolower( $resultData['hash'] ) == strtolower( $txhash ) &&
										strtoupper( $resultData['tokenSymbol'] ) == $tokenSymbolVerify &&
										strtolower( $resultData['from'] ) == strtolower( $getRetirement->eth_address ) &&
										strtolower( $resultData['to'] ) == strtolower( $getRetirement->retire_receiver_address )
									){
										$where_data = array('id'	=>	$getRetirement->id );
										$update_data = array(
											'retire_amount'			=>	$responseAmount,
											'retire_status'			=> 1,
											'retire_confirm_date'	=> date_i18n('Y-m-d H:i:s'),
											'last_update'			=> date_i18n('Y-m-d H:i:s'),
										);
										$updated = $wpdb->update($tableRetirement, $update_data, $where_data);
										if( $updated ){

											$logs = sprintf( __('Retirement of %s CSR for username: %s, email: %s,

											After 20 blocks were confirmed, the API confirmed the retirement amount of %s CSR for transaction: %s at %s', CIP_TXTDOMAIN), $getRetirement->retire_amount_log, $getRetirement->username, $getRetirement->email, $responseAmount, $txhash, date_i18n('d/m/Y H:i A') );
											create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );

											$out = array( "error" => 0, 'data' => $confirmBlock .' - '.$txhash );

											do_action('refresh_csr_remaining_data_from_retirement_confirm', 'retirement_confirm');
										}
									}else{

										$where_data = array('id'	=>	$getRetirement->id );
										$update_data = array(
											'retire_status'	=>	2
										);
										$updated = $wpdb->update($tableRetirement, $update_data, $where_data);

										$logs = sprintf( __('Confirmation block Validation failed for username: %s, email: %s, CSR Retiremnet amount %s, Transaction %s, Expecting Transaction hash %s and user address %s but recieved Transaction hash %s and user address %s at %s', CIP_TXTDOMAIN), $getRetirement->username, $getRetirement->email, $getRetirement->retire_amount, $txhash, $txhash, $getRetirement->eth_address, $resultData['hash'], $resultData['from'], date_i18n('d/m/Y H:i A') );
										create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
									}
								}else{
									$logs = sprintf( __('Retirement confirmation failed to get a response from the api after 20 blocks. username: %s, email: %s, Transaction confirmation %s, at %s', CIP_TXTDOMAIN), $getRetirement->username, $getRetirement->email, $txhash, date_i18n('d/m/Y H:i A') );
									create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
								}

							}else if( $confirmBlock >= 1 && $getRetirement->retire_amount <= 0 ){

								$ethResponseBlock = get_etherscan_transaction_by_block_response( $blockNumberDec, $getRetirement->eth_address, $txhash, $thisTokenType );

								if( $ethResponseBlock['status'] && isset( $ethResponseBlock['result'][0] ) ){
									$resultData = $ethResponseBlock['result'][0];
									$converter = new Bezhanov\Ethereum\Converter();
									$responseAmount = $convertedValue = floatval( $converter->fromWei( (string)$resultData['value'] , 'ether') );

									$where_data = array('id'	=>	$getRetirement->id );
									$update_data = array(
										'retire_amount'	=>	$responseAmount
									);
									$updated = $wpdb->update($tableRetirement, $update_data, $where_data);
								}


							}else{
								$out = array( "error" => 0, 'data' => $confirmBlock );
							}
							echo wp_json_encode( $out );
							// exit;

						}


					}
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
function get_etherscan_transaction_by_block_response( $blockNumber = 0, $eth_address = '', $transaction_hash = '', $token = 'csr' ){

	$token = strtolower( $token );
	if( $token == 'csr25' ){
		$csr_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
		$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');
		$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_api') : get_option('csr25_wallet_api_mode_test_api');
		$sourceApiUrl = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
	}else{
		$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
		$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
		$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_api') : get_option('csr_wallet_api_mode_test_api');
		$sourceApiUrl = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
	}

	$startblock = $blockNumber - 1;
	$endblock = $blockNumber + 1;

	$address = $eth_address;

	$getTxnUrl = add_query_arg( array(
		'module' 			=> 'account',
		'action' 			=> 'tokentx',
		'contractaddress'	=> $contractaddress,
		'address' 			=> $address,
		'page' 				=> 1,
		'offset' 			=> 1000,
		'startblock' 		=> $startblock,
		'endblock' 			=> $endblock,
		'sort' 				=> 'desc',
		'apikey'			=>	$apikey
	), $sourceApiUrl );
	$request = wp_remote_get( $getTxnUrl, array( 'timeout'     => 15 ) );
	if( !is_wp_error( $request ) ) {
		$bodyResponse = json_decode( wp_remote_retrieve_body( $request ), true );

		if( $bodyResponse['status'] ){
			foreach( $bodyResponse['result'] as $result ){
				if( strtolower( $result['hash'] ) == strtolower( $transaction_hash ) ){
					$bodyResponse['result'][0] = $result;
					break;
				}
			}
		}

	}else{
		$error_message = $request->get_error_message();
		$bodyResponse = json_decode( '{"status":0,"result":"'.$error_message.'"}', true );
	}

	// create_cip_logs_entery( 1, 'member_deposit_log', '', 'member', json_encode( $bodyResponse ) . $getTxnUrl );

	return $bodyResponse;
}
add_action('wp_ajax_csr_retirement_view_act','csr_retirement_view_act_callback');
function csr_retirement_view_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyCsrRetirementViewyX_' ) ){
		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['thiseth'] ."");
		if( $getMember ){
			$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE email = '".$getMember->email."' AND token = '".$_POST['plastic_credit']."' AND eth_address = '".$getMember->eth_address."' ");
			$formHtml = "<p>".__('No record found',CIP_TXTDOMAIN)."</p>";
			if( $getRetirements ){
				$formHtml = '<table id="retirement_view_table"  data-filter-control="true"  data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered">';
				$formHtml .= '<thead>
				<tr>
					<th data-field="id" class="id" data-switchable="false">'. __('Id',CIP_TXTDOMAIN).'</th>
					<th data-field="eth_address" data-sortable="false" data-switchable="false" class="eth_address">'.__('CSR Wallet Address',CIP_TXTDOMAIN).'</th>
					<th data-field="retire_date" data-sortable="false" data-switchable="false" class="retire_date">'.__('Retire date',CIP_TXTDOMAIN).'</th>
					<th data-field="eth_balance" class="eth_balance" data-sortable="false" data-switchable="false">'.__('Retired Amount',CIP_TXTDOMAIN).'</th>
					<th data-field="retire_status" class="retire_status" data-sortable="false" data-switchable="false">'.__('Status',CIP_TXTDOMAIN).'</th>
					<th data-field="retire_visibility" class="retire_visibility" data-sortable="false" data-switchable="false">'.__('Visibility',CIP_TXTDOMAIN).'</th>
					<th data-field="retire_pdf" class="retire_pdf" data-sortable="false" data-switchable="false"><i class="fa fa-tasks" aria-hidden="true"></i></th>
				</tr>
				</thead>
				<tbody>';
				$countLoop = 1;
				$pending_count = 0;
				foreach( $getRetirements as $getRetirement ){

					$thisTokenType = strtolower( $getRetirement->token );

					if( !empty( $getRetirement->eth_address ) ){
						$columnsDataValMask = substr($getRetirement->eth_address, 0, 6) . '...' . substr($getRetirement->eth_address, -6);
						$columnsDataVal = '<a href="https://etherscan.io/address/'. $getRetirement->eth_address . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$getRetirement->eth_address.'" >'.$columnsDataValMask.'</a>';
						if( $getMember->sign_verify == 1 ){
							$columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />';
						}
					}else{
						$is_edit_eth = true;
						$columnsDataVal = '—';
					}

					$retire_status_og = $getRetirement->retire_status;

					$retire_amount = $getRetirement->retire_amount;

					$retire_status = __('Pending',CIP_TXTDOMAIN);
					$retire_status_count = "";
					$pdf_link = '—';
					$visibilityHtml = '—';
					$public_suffix = '';
					$public_current = '';
					$private_current = '';
					$restricted_current = '';

					if( $retire_status_og == 0 ){

						if( $thisTokenType == 'csr25' ){
							$csr_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
							$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_api') : get_option('csr25_wallet_api_mode_test_api');
							$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
							$tokenSymbolVerify = ( $csr_wallet_api_mode == 'live' ) ? 'CSR25' : 'TESTCSR25';
						}else{	
							$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
							$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_api') : get_option('csr_wallet_api_mode_test_api');
							$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
							$tokenSymbolVerify = ( $csr_wallet_api_mode == 'live' ) ? 'CSR' : 'TESTCSR';
						}

						$txhash = $getRetirement->retire_transhash;
						$csr_retirement_confirmation_block = ( !empty( get_option('csr_retirement_confirmation_block') ) ) ? get_option('csr_retirement_confirmation_block') : 0 ;
						$getTxnUrl = add_query_arg( array(
							'module' => 'proxy',
							'action' => 'eth_getTransactionByHash',
							'txhash' => $txhash,
							'apikey'=>	$apikey
						), $endpoint );

						$request = wp_remote_get( $getTxnUrl );
						if( !is_wp_error( $request ) ) {
							$body = wp_remote_retrieve_body( $request );
							$data = json_decode( $body, true );
							if( isset( $data['result'] ) ){
								$blockNumberHex = $data['result']['blockNumber'];
								$blockNumberDec = hexdec( $blockNumberHex );

								$getBlockUrl = add_query_arg( array(
									'module' => 'proxy',
									'action' => 'eth_blockNumber',
									'apikey'=>	$apikey
								), $endpoint );
								$blockRequest = wp_remote_get( $getBlockUrl );
								if( !is_wp_error( $blockRequest ) ) {
									$blockBody = wp_remote_retrieve_body( $blockRequest );
									$blockData = json_decode( $blockBody, true );
									if( isset( $blockData['result'] ) ){
										$blockResult = hexdec( $blockData['result'] );
									}
									if( $blockNumberDec && $blockResult ){
										$confirmBlock = $blockResult - $blockNumberDec;
										if( $confirmBlock >= $csr_retirement_confirmation_block ){

											$ethResponseBlock = get_etherscan_transaction_by_block_response( $blockNumberDec, $getRetirement->eth_address, $txhash, $thisTokenType );

											if( $ethResponseBlock['status'] && isset( $ethResponseBlock['result'][0] ) ){
												$resultData = $ethResponseBlock['result'][0];
												$converter = new Bezhanov\Ethereum\Converter();
												$responseAmount = $convertedValue = floatval( $converter->fromWei( (string)$resultData['value'] , 'ether') );
												if( strtolower( $resultData['hash'] ) == strtolower( $txhash ) &&
													strtoupper( $resultData['tokenSymbol'] ) == $tokenSymbolVerify &&
													strtolower( $resultData['from'] ) == strtolower( $getRetirement->eth_address ) &&
													strtolower( $resultData['to'] ) == strtolower( $getRetirement->retire_receiver_address )
												){
													$where_data = array('id'	=>	$getRetirement->id );
													$update_data = array(
														'retire_amount'			=> $responseAmount,
														'retire_status'			=> 1,
														'retire_confirm_date'	=> date_i18n('Y-m-d H:i:s'),
														'last_update'			=> date_i18n('Y-m-d H:i:s'),
													);

													$retire_amount = $responseAmount;

													$updated = $wpdb->update($tableRetirement, $update_data, $where_data);
													if( $updated ){
														$retire_status_og = 1;

														$logs = sprintf( __('Retirement of %s CSR for username: %s, email: %s,

														After 20 blocks were confirmed, the API confirmed the retirement amount of %s CSR for transaction: %s at %s', CIP_TXTDOMAIN), $getRetirement->retire_amount_log, $getRetirement->username, $getRetirement->email, $responseAmount, $txhash, date_i18n('d/m/Y H:i A') );
														create_cip_logs_entery( 0, 'retire', '','member', $logs, true );

														do_action('refresh_csr_remaining_data_from_retirement_confirm', 'retirement_confirm');
													}
												}else{

													$where_data = array('id'	=>	$getRetirement->id );
													$update_data = array(
														'retire_status'	=>	2
													);
													$retire_amount = $responseAmount;
													$updated = $wpdb->update($tableRetirement, $update_data, $where_data);

													$logs = sprintf( __('Confirmation block Validation failed for username: %s, email: %s, CSR Retiremnet amount %s, Transaction %s, Expecting Transaction hash %s and user address %s but recieved Transaction hash %s and user address %s at %s', CIP_TXTDOMAIN), $getRetirement->username, $getRetirement->email, $getRetirement->retire_amount, $txhash, $txhash, $getRetirement->eth_address, $resultData['hash'], $resultData['from'], date_i18n('d/m/Y H:i A') );

													create_cip_logs_entery( 0, 'retire', '','member', $logs, true );
												}
											}else{

												$logs = sprintf( __('Retirement confirmation failed to get a response from the api after 20 blocks. username: %s, email: %s, Transaction confirmation %s, at %s', CIP_TXTDOMAIN), $getRetirement->username, $getRetirement->email, $txhash, date_i18n('d/m/Y H:i A') );
												create_cip_logs_entery( 0, 'retire', '','member', $logs, true  );
											}


										}else if( $confirmBlock >= 1 && $getRetirement->retire_amount <= 0 ){

											$ethResponseBlock = get_etherscan_transaction_by_block_response( $blockNumberDec, $getRetirement->eth_address, $txhash, $thisTokenType );

											if( $ethResponseBlock['status'] && isset( $ethResponseBlock['result'][0] ) ){
												$resultData = $ethResponseBlock['result'][0];
												$converter = new Bezhanov\Ethereum\Converter();
												$responseAmount = $convertedValue = floatval( $converter->fromWei( (string)$resultData['value'] , 'ether') );

												$where_data = array('id'	=>	$getRetirement->id );
												$update_data = array(
													'retire_amount'	=>	$responseAmount
												);
												$retire_amount = $responseAmount;
												$updated = $wpdb->update($tableRetirement, $update_data, $where_data);
											}

											$retire_status_count = '<p>'.sprintf( __('(%s of %s confirmations complete.)',CIP_TXTDOMAIN), $confirmBlock, $csr_retirement_confirmation_block ).'</p>';

										}else{
											$retire_status_count = '<p>'.sprintf( __('(%s of %s confirmations complete.)',CIP_TXTDOMAIN), $confirmBlock, $csr_retirement_confirmation_block ).'</p>';
										}
									}
								}else{
									// $retire_status_count = $blockRequest->get_error_message();
								}

							}
						}else{
							// $retire_status_count = $request->get_error_message();
						}
					}

					$refresh_count_btn = "";
					if( $retire_status_og == 0 ){
						$refresh_count_btn .= '<a href="javascript:void(0);" class="refreshRetirementDetail" data-sync="'.$getMember->id.'"><span class="fa fa-sync-alt"></span> '. __("Refresh blocks",CIP_TXTDOMAIN).'</a>';
					}

					if( $retire_status_og == 2 ){
						$retire_status = __('Incomplete',CIP_TXTDOMAIN);
					}

					if( $retire_status_og == 1 ){
						$retire_status = __('Complete',CIP_TXTDOMAIN);
						$pdf_url = add_query_arg( array(
							'retireid'	=>	$getRetirement->id,
							'action' => 'retire_pdf',
						), admin_url('admin-ajax.php') );

						$radioPrivateName = $getRetirement->id;
						$radioRestrictedName = $getRetirement->id;
						$radioPublicName = $getRetirement->id;

						$public_suffix = ( $getRetirement->retire_visibility != 3 ) ? __('(Recommended)') : '' ;
						$private_current = ( $getRetirement->retire_visibility == 1 ) ? __('(Current)') : '' ;
						$restricted_current = ( $getRetirement->retire_visibility == 2 ) ? __('(Current)') : '' ;
						$public_current = ( $getRetirement->retire_visibility == 3 ) ? __('(Current)') : '' ;

						$selected_retire_status = "";
						if( $getRetirement->retire_visibility == 1 ){
							$selected_retire_status = __('Private',CIP_TXTDOMAIN);
						}else if( $getRetirement->retire_visibility == 2 ){
							$selected_retire_status = __('Restricted',CIP_TXTDOMAIN);
						}else if( $getRetirement->retire_visibility == 3 ){
							$selected_retire_status = __('Public',CIP_TXTDOMAIN);
						}

						$pdf_link = '<a href="'.$pdf_url.'" target="_blank"><i class="fa fa-download" aria-hidden="true"></i></a>';
					}
					$retire_date_formatted = '—';
					try {
						$retire_date = DateTime::createFromFormat('Y-m-d H:i:s', $getRetirement->retire_date);
						$retire_date_formatted = $retire_date->format('d/m/Y');
					} catch (\Throwable $th) {
						$retire_date_formatted = '—';
					}

					$radioPrivateName = $getRetirement->id.'_visibility';
					$radioRestrictedName = $getRetirement->id.'_visibility';
					$radioPublicName = $getRetirement->id.'_visibility';


					if( $getRetirement->retire_status == 0 && $retire_amount <= 0 ){
						$retire_amount_val = '-';
					}else{
						$retire_amount_val = $retire_amount;
					}

					$formHtml .= '<tr data-rth="'.$getRetirement->id.'">
					<td>'.$countLoop.'</td>
					<td>'.$columnsDataVal.'</td>
					<td>'.$retire_date_formatted.'</td>
					<td>'.$retire_amount_val.'</td>
					<td>'.$retire_status. $retire_status_count . $refresh_count_btn .'</td>
					<td>'.$selected_retire_status.'</td>
					<td>'.$pdf_link.'</td>
					</tr>';
					$countLoop++;
				}
				$formHtml .= '</tbody></table>';
				$formHtml .= '<button type="button" class="btn btn-secondary" data-dismiss="modal">'. __("Close",CIP_TXTDOMAIN).'</button><br/><br/>';
				$formHtml .= '<form class="form-inline" style="column-gap:15px;">
				<label class="pt-0" for="visibility_box">'.__('Visibility', CIP_TXTDOMAIN).'</label>
				<select id="visibility_box" name="visibility_box" class="form-control" data-visible="'.$getMember->eth_address.'" data-token="'. $_POST['plastic_credit'] .'">
					<option value="" disable selected>'.__('--Select Visibility--', CIP_TXTDOMAIN).'</option>
					<option value="1">'.__('Private', CIP_TXTDOMAIN).'</option>
					<option value="2">'.__('Restricted', CIP_TXTDOMAIN).'</option>
					<option value="3">'.__('Public', CIP_TXTDOMAIN).'</option>
				</select></form>
				<br/>
				<p><b>'.__('Private', CIP_TXTDOMAIN).':</b>'.sprintf( __('Your name and its link to the blockchain address %s and the retirement of CSR is private and can only be seen by you',CIP_TXTDOMAIN), $getRetirement->eth_address ).'</p>
				<p><b>'.__('Restricted', CIP_TXTDOMAIN).':</b>'.sprintf( __('Your name and its link to the blockchain address %s and the retirement of CSR is private and can only be seen by you and other holders of CSR when they are logged into CSRnow',CIP_TXTDOMAIN), $getRetirement->eth_address ).'</p>
				<p><b>'.__('Public', CIP_TXTDOMAIN).':</b>'.sprintf( __('Your name and its link to the blockchain address %s and the retirement of CSR is PUBLIC and can be seen by any visitor to CSRnow.com',CIP_TXTDOMAIN), $getRetirement->eth_address ).'</p>
				';
				$formHtml .= '<br><p><span class="form_response"></span></p>';
			}else{
				$out = array( "error" => 1, 'msg' => $formHtml );
				echo wp_json_encode($out);
				exit;
			}

			$out = array( "error" => 0, 'msg' => '' ,'data' => $formHtml );
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_get_all_retire_csr_amount','cip_get_all_retire_csr_amount_callback');
function cip_get_all_retire_csr_amount_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	// $out = array( "error" => 1, 'msg' => $_POST );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( wp_verify_nonce( $_POST['_micro'],'_XyGetAllRetireCsrCoinyX_' ) ){

		$decrypted_thisToken_raw = base64_decode( $_POST['thisToken'] );
		$thiseth = preg_replace(sprintf('/%s/', md5( strtoupper( $_POST['thisTokenType'] ) ) ), '', $decrypted_thisToken_raw);
		if( $_POST['thiseth'] != $thiseth ){
			$out = array( "error" => 1, 'msg' => __('Authentication failed.', CIP_TXTDOMAIN) );
			echo wp_json_encode($out);
			exit;
		}

		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE id=".$_POST['thiseth'] ." AND email = '".$refAccount."' AND sign_verify = 1");
		if( $getMember ){
			$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
			$tokenaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');

			$_POST['thistoggle'] = true;

			if( $_POST['thistoggle'] == "true" ){
				$eth_balance = cip_get_ether_balance( $getMember->eth_address, $_POST['thisTokenType'] );
				if( !is_numeric( $eth_balance ) || $eth_balance <= 0 ){
					$out = array( "error" => 1, 'msg' => sprintf( __('No CSR at blockchain address %s',CIP_TXTDOMAIN), $getMember->eth_address ) );
					echo wp_json_encode($out);
					exit;
				}
				$txt = sprintf( __('You are about to retire %s CSR',CIP_TXTDOMAIN), number_format( $eth_balance ) );
				$out = array( "error" => 0, 'msg' => __('Success',CIP_TXTDOMAIN),'data' => $txt, 'value' => floatval( bcadd($eth_balance, 0, 2) )  );
			}else{
				$txt = '';
				$out = array( "error" => 0, 'msg' => __('Success',CIP_TXTDOMAIN),'data' => $txt, 'value' => 0 );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_retire_pdf','cip_retire_pdf_generate_callback');
// add_action('wp_ajax_nopriv_retire_pdf','cip_retire_pdf_generate_callback');
function cip_retire_pdf_generate_callback(){
	global $wpdb;
	if( isset( $_GET['retireid'] ) && !empty( $_GET['retireid'] ) ){
		$retireid = $_GET['retireid'];
		$site = get_site_url();
		$tableRetirement = $wpdb->prefix.'retirement_data';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$header_img = $site."/wp-content/uploads/2021/10/Asset-10.png";
		$bg_img = $site."/wp-content/plugins/cip-helper/images/csr_retirement_event.jpg";
		require_once  dirname(__DIR__, 1) . '/cip-helper/includes/fpdf/fpdf.php';
		//require_once dirname(__DIR__, 1) ."/cip-helper/phpqrcode/qrlib.php";

		$refAccount = '-';
		if( current_user_can( 'supportagent' ) || current_user_can( 'member_assistant' ) ){
			$getRetireEmail = $wpdb->get_row("SELECT * FROM $tableRetirement WHERE id=".$retireid." AND retire_status = 1");
			if( $getRetireEmail ){
				$refAccount = $getRetireEmail->email;
			}
		}else{
			$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		}
		$getRetirement = $wpdb->get_row("SELECT * FROM $tableRetirement WHERE id=".$retireid." AND email = '".$refAccount."' AND retire_status = 1");
		if( $getRetirement ){
			class PDF extends FPDF{
				function SetCellMargin($margin){
					$this->cMargin = $margin;
				}
			}
			if($getRetirement->token == 'CSR25'){
				$bg_img = $site."/wp-content/plugins/cip-helper/images/csr25_retirement_event.jpg";
			}
			$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
			$txnHash = $getRetirement->retire_transhash;
			// $txnUrl = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/'.$getRetirement->retire_transhash : 'https://rinkeby.etherscan.io/tx/'.$getRetirement->retire_transhash;

			// $pdfLine = sprintf( __('%s %s retired %s CSR from CSR Wallet address %s',CIP_TXTDOMAIN), $getRetirement->first_name, $getRetirement->last_name, $getRetirement->retire_amount, $getRetirement->eth_address  );
			$pdfLine = sprintf( __('%s %s retired %s CSR from %s',CIP_TXTDOMAIN), $getRetirement->first_name, $getRetirement->last_name, $getRetirement->retire_amount, $getRetirement->eth_address  );
			$blockNumber = cipGetBlockByHash( $getRetirement->retire_transhash );
			// $pdfLine2 = sprintf( __('This is permanently recorded on the Ethereum Blockchain in Block [%s] and with transaction hash %s',CIP_TXTDOMAIN), $blockNumber, $getRetirement->retire_transhash  );

			$hiLine = $getRetirement->first_name . ' ' . $getRetirement->last_name;

			$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$getRetirement->email."' ORDER BY id DESC LIMIT 1");
			if( $getTokenData ){
				if( !empty( $getTokenData->first_name ) || !empty( $getTokenData->last_name ) ){
					$hiLine = $getTokenData->first_name . ' ' . $getTokenData->last_name;
				}
			}

			$getRetirementSetting = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE email = '".$refAccount."' ");
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$hiLine = $getRetirementSetting->company_name;
				}
			}

			$retire_date_formatted = '—';
			try {
				$retire_date = DateTime::createFromFormat('Y-m-d H:i:s', $getRetirement->retire_confirm_date);
				$retire_date_formatted = $retire_date->format('d/m/Y');
			} catch (\Throwable $th) {
				$retire_date_formatted = '—';
			}

			// $pdf = new PDF('L');
			$pdf = new PDF('L','mm',array(928.15833333,656.43125));
			$pdf->AliasNbPages();
			$pdf->AddPage();
			$pdf->Image($bg_img, 0, 0, '', '', "jpg");
			$pdf->AddFont('AmalfiCoastConvert','','AmalfiCoastConvert.php');
			$pdf->AddFont('MontserratR','','MontserratR.php');

			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('AmalfiCoastConvert','',53);

			$hiLine = iconv('UTF-8', 'windows-1252', $hiLine);
			$pdf->Text(88, 226.5, $hiLine);

			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('MontserratR','',30);

			$pdf->SetXY(52.5 , 280);
			$pdf->Cell(155,16,'Amount of retired CSR :', "0,0,0,0","0","l");

			$retire_amount = floatval( bcadd( $getRetirement->retire_amount, 0, 2) );
			if (fmod($retire_amount, 1) !== 0.0) {
				$pdf->Cell(310,16,number_format( $retire_amount, 2 ), "0,0,0,0","1","l");
			}else{
				$pdf->Cell(310,16,number_format( $retire_amount ), "0,0,0,0","1","l");
			}
			// $pdf->Text(190, 313, $getRetirement->retire_amount);	//1

			$pdf->SetXY(52.5 , 296);
			$pdf->Cell(155,16,'Retirement date :', "0,0,0,0","0","l");
			$pdf->Cell(310,16,$retire_date_formatted, "0,0,0,0","1","l");
			// $pdf->Text(158, 327, $retire_date_formatted);	//2


			$pdf->SetXY(52.5 , 312);
			$pdf->Cell(155,16,'Retiring Wallet Address :', "0,0,0,0","0","l");
			$pdf->Cell(310,16,$getRetirement->eth_address, "0,0,0,0","1","l");
			// $pdf->Text(215, 341, $getRetirement->eth_address);	//3

			/* $kgs = $getRetirement->retire_amount / 10;
			$pdf->SetXY(52.5 , 352);
			$pdf->MultiCell(465,13, sprintf( 'This certificate confirms the retirement event of CSR Plastic Credit which confirms the removal of %s kg of Plastic waste from the environment.', cip_pdf_number_formater( $kgs ) ) , "0,0,0,0","l"); */


			$pdf->SetXY(52.5 , 328);
			$pdf->Cell(155,15,'Block number :', "0,0,0,0","0","l");
			$pdf->Cell(310,15,$blockNumber, "0,0,0,0","1","l");
			// $pdf->Text(148, 354, $blockNumber);	//4

			$pdf->SetXY(52.5 , 344);
			$pdf->Cell(155,16,'Transaction hash :', "0,0,0,0","l");
			$pdf->MultiCell(310,16,$getRetirement->retire_transhash, "0,0,0,0","l");
			// $pdf->SetXY(52.5 , 378);
			// $pdf->Text(53, 380, $getRetirement->retire_transhash);	//5

			$kgs = $getRetirement->retire_amount / 10;
			$pdf->SetXY(52.5 , 390);
			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('MontserratR','',34);
			$pdf->MultiCell(465,16, sprintf( 'This certificate confirms the retirement event of CSR Plastic Credit which confirms the removal of %s kg of Plastic waste from the environment.', cip_pdf_number_formater( $kgs ) ) , "0,0,0,0","C");

			$qr_url = add_query_arg( array(
				'txnHash'	=>	$txnHash,
				'action' => 'retire_txn_qrcode',
			), admin_url('admin-ajax.php') );
			$pdf->Image($qr_url, 104.3, 525, 60, 60, "png");
			$pdf->SetTitle("CSR Plastic Waste Retirement Event Certificate");

			$pdf->Output('I', 'CSR Plastic Waste Retirement Event Certificate.pdf');
		}else{
			wp_redirect( site_url() );
			exit();
		}
	}
	exit;
}

add_action('wp_ajax_total_retire_pdf','cip_total_retire_pdf_callback');
function cip_total_retire_pdf_callback(){
	global $wpdb;
	if( isset( $_GET['retireaddress'] ) && !empty( $_GET['retireaddress'] ) ){
		$retireaddress = $_GET['retireaddress'];
		$site = get_site_url();
		$tableRetirement = $wpdb->prefix.'retirement_data';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$header_img = $site."/wp-content/uploads/2021/10/Asset-10.png";
		$bg_img = $site."/wp-content/plugins/cip-helper/images/csr_retirement_total.jpg";
		require_once  dirname(__DIR__, 1) . '/cip-helper/includes/fpdf/fpdf.php';
		if(isset($_GET['plastic_credit']) && $_GET['plastic_credit']){
			$token_query = "AND token = '".$_GET['plastic_credit']."'";
		}else{
			$token_query = "";
		}

		$refAccount = '-';
		if( current_user_can( 'supportagent' ) || current_user_can( 'member_assistant' )  ){
			$getRetireEmail = $wpdb->get_row("SELECT * FROM $tableRetirement WHERE eth_address='".$retireaddress."' AND retire_status = 1 ".$token_query."");
			if( $getRetireEmail ){
				$refAccount = $getRetireEmail->email;
			}
		}else{
			$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		}

		// $refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		$total_retired_csr = 0;
		$fullname = "";
		$latest_retirement_date = "";
		$getRetirement = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE email = '".$refAccount."' AND eth_address = '".$retireaddress."' AND retire_status = 1 ".$token_query."");
		if( $getRetirement ){
			class PDF extends FPDF{
				function SetCellMargin($margin){
					$this->cMargin = $margin;
				}
			}
			if($_GET['plastic_credit'] == 'CSR25'){
				$bg_img = $site."/wp-content/plugins/cip-helper/images/csr25_retirement_total.jpg";
			}
			foreach( $getRetirement as $getRetire ){
				$total_retired_csr += $getRetire->retire_amount;
				$fullname = $getRetire->first_name . ' ' . $getRetire->last_name;
				$latest_retirement_date = $getRetire->retire_confirm_date;
			}

			$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' ".$token_query." ORDER BY id DESC LIMIT 1");
			if( $getTokenData ){
				if( !empty( $getTokenData->first_name ) || !empty( $getTokenData->last_name ) ){
					$fullname = $getTokenData->first_name . ' ' . $getTokenData->last_name;
				}
			}

			$getRetirementSetting = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE email = '".$refAccount."'");
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$fullname = $getRetirementSetting->company_name;
				}
			}

			//#5273
			$retire_date_formatted = '—';
			if( !empty( $latest_retirement_date ) ){
				try {
					$retire_date = DateTime::createFromFormat('Y-m-d H:i:s', $latest_retirement_date);
					$retire_date_formatted = $retire_date->format('d/m/Y');
				} catch (\Throwable $th) {
					$retire_date_formatted = '—';
				}
			}

			// $pdf = new PDF('L');
			$pdf = new PDF('L','mm',array(928.15833333,656.43125));
			$pdf->AliasNbPages();
			$pdf->AddPage();
			$pdf->Image($bg_img, 0, 0, '', '', "jpg");
			$pdf->AddFont('AmalfiCoastConvert','','AmalfiCoastConvert.php');
			$pdf->AddFont('MontserratR','','MontserratR.php');

			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('AmalfiCoastConvert','',53);

			$fullname = iconv('UTF-8', 'windows-1252', $fullname);
			$pdf->Text(88, 247, $fullname);

			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('MontserratR','',30);

			$pdf->SetXY(52.5 , 300);
			$pdf->Cell(155,16,'Total amount of retired CSR :', "0,0,0,0","0","l");

			$total_retired_csr = floatval( bcadd( $total_retired_csr, 0, 2) );

			if (fmod($total_retired_csr, 1) !== 0.0) {
				$pdf->Cell(310,16,number_format( $total_retired_csr, 2 ), "0,0,0,0","1","l");
			}else{
				$pdf->Cell(310,16,number_format( $total_retired_csr ), "0,0,0,0","1","l");
			}
			// $pdf->Text(215, 313, $total_retired_csr);	//1

			$pdf->SetXY(52.5 , 316);
			$pdf->Cell(155,16,'Certificate date :', "0,0,0,0","0","l");
			$pdf->Cell(310,16,$retire_date_formatted, "0,0,0,0","1","l");
			// $pdf->Cell(310,16,date_i18n('d/m/Y'), "0,0,0,0","1","l");
			// $pdf->Text(158, 327, date_i18n('d/m/Y') );	//2

			$pdf->SetXY(52.5 , 332);
			$pdf->Cell(155,16,'Retiring Wallet Address :', "0,0,0,0","0","l");
			$pdf->Cell(310,16,$retireaddress, "0,0,0,0","1","l");
			// $pdf->Text(215, 341, $retireaddress);	//3

			$kgs = $total_retired_csr / 10;
			$pdf->SetXY(52.5 , 365);
			$pdf->SetTextColor(0, 0, 0);
			$pdf->SetFont('MontserratR','',34);
			$pdf->MultiCell(465,16, sprintf( 'This certificate represents the retirement of CSR Plastic Credit which confirms the removal of %s kg of Plastic waste from the environment.', cip_pdf_number_formater( $kgs ) ) , "0,0,0,0","C");

			$qr_url = add_query_arg( array(
				'ethHash'	=>	$retireaddress,
				'action' => 'retire_total_qrcode',
			), admin_url('admin-ajax.php') );
			$pdf->Image($qr_url, 104, 515, 60, 60, "png");

			$pdf->SetTitle("CSR Plastic Waste Retirement Certificate");

			$pdf->Output('I','CSR Plastic Waste Retirement Certificate.pdf');
		}else{
			wp_redirect( site_url() );
			exit();
		}
	}
	exit;
}
add_action('wp_ajax_retire_txn_qrcode','cip_retire_txn_qrcode_cb');
add_action('wp_ajax_nopriv_retire_txn_qrcode','cip_retire_txn_qrcode_cb');
function cip_retire_txn_qrcode_cb(){
	require_once dirname(__DIR__, 1) ."/cip-helper/phpqrcode/qrlib.php";

	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$txnUrl = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/'.$_GET['txnHash'] : 'https://sepolia.etherscan.io/tx/'.$_GET['txnHash'];
	// QRcode::png( $txnUrl,'','','','','','','0xd34743' );
	QRcode::png( $txnUrl, false, QR_ECLEVEL_M, 3, 0, false );
	exit;
}
add_action('wp_ajax_retire_total_qrcode','cip_retire_total_qrcode_cb');
add_action('wp_ajax_nopriv_retire_total_qrcode','cip_retire_total_qrcode_cb');
function cip_retire_total_qrcode_cb(){
	require_once dirname(__DIR__, 1) ."/cip-helper/phpqrcode/qrlib.php";

	$qr_url = add_query_arg( array(
		'address'	=>	$_GET['ethHash'],
	), get_permalink( get_page_by_path('holders-retirement') ) );
	QRcode::png( $qr_url, false, QR_ECLEVEL_M, 3, 0, false );
	exit;
}
function cipGetBlockByHash( $hash = '' ){
	$block = "";
	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$contractaddress = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_tkn') : get_option('csr_wallet_api_mode_test_tkn');
	$apikey = ( $csr_wallet_api_mode == 'live' ) ? get_option('csr_wallet_api_mode_live_api') : get_option('csr_wallet_api_mode_test_api');
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://api.etherscan.io/api' : 'https://api-sepolia.etherscan.io/api';
	$txhash = $hash;
	$getTxnUrl = add_query_arg( array(
		'module' => 'proxy',
		'action' => 'eth_getTransactionByHash',
		'txhash' => $txhash,
		'apikey'=>	$apikey
	), $endpoint );
	$request = wp_remote_get( $getTxnUrl );
	if( is_wp_error( $request ) ) {
		$block = "";
	}
	$body = wp_remote_retrieve_body( $request );
	$data = json_decode( $body, true );
	if( isset( $data['result'] ) ){
		$blockNumberHex = $data['result']['blockNumber'];
		$blockNumberDec = hexdec( $blockNumberHex );
		$block = $blockNumberDec;
	}
	return $block;
}
add_action('wp_ajax_csr_retirement_update_act','cip_csr_retirement_update_act_callback');
function cip_csr_retirement_update_act_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirement = $wpdb->prefix.'retirement_data';

	$tokenType = 'CSR';
	if( isset( $_POST['thisToken'] ) && strtoupper( $_POST['thisToken'] ) == 'CSR25' ){
		$tokenType = strtoupper( $_POST['thisToken'] );
	}

	if( wp_verify_nonce( $_POST['_micro'],'_XyCsrRetirementUpdateyX_' ) ){
		$getMember = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$refAccount."' AND eth_address='".$_POST['thisvisibilitypoint']."' AND sign_verify = 1");
		if( $getMember ){
			$where_data = array('email' => $getMember->email, 'eth_address'	=> $_POST['thisvisibilitypoint'], 'token' => $tokenType );
			$update_data = array(
				'retire_visibility'	=> $_POST['thisvisibility'],
				'last_update'		=> date_i18n('Y-m-d H:i:s'),
			);
			$updated = $wpdb->update($tableRetirement, $update_data, $where_data);
			if( $updated ){
				$out = array( "error" => 0, 'msg' => __('Update successfully') );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);
    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;
    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        // 's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k > 0) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
function cip_convert_csr_by_price( $price = 10 ){
	$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
	if($hall_of_fame_price_type == 'csr'){
		$selling_price_csr = ( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
	}else{
		$selling_price_csr = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
	}
	$csr_amount = csr_to_two_decimal( $price / $selling_price_csr, true );
	return $csr_amount;
}
function cip_convert_kgs_by_price( $price = 10 ){
	$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
	if($hall_of_fame_price_type == 'csr'){
		$selling_price_csr = ( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
	}else{
		$selling_price_csr = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
	}
	$csr_amount = $price / $selling_price_csr;
	$kgs = csr_to_two_decimal( $csr_amount / 10, true );
	return $kgs;
}
function cip_convert_csr_by_price_pdf( $price = 10, $selling_price = 1 ){
	$csr_amount = csr_to_two_decimal( $price / $selling_price, true );
	return $csr_amount;
}
add_filter( 'gform_field_content', function( $input, $field ) {
	if ( $field->type == 'email' ) {
		$autocomplete = 'password';
		// $autocomplete = gw_get_browser_name( $_SERVER['HTTP_USER_AGENT'] ) === 'Chrome' ? 'password' : 'off';
		return preg_replace( '/<(input|textarea)/', '<${1} autocomplete="' . $autocomplete . '" ', $input );
	}
	return $input;
}, 11, 2 );
add_action('wp_ajax_cip_add_csr_scheduler','cip_add_csr_scheduler_callback');
function cip_add_csr_scheduler_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableScheduler = $wpdb->prefix.'csr_scheduler';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsmCSRScheduleraddxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$status = ( $_POST['price_type'] == 'prompt' ) ? 'active' : 'pending';
		$schedule_time = ( $_POST['price_type'] == 'prompt' ) ? gmdate('Y-m-d H:i') : sprintf( '%s %s:%s', $_POST['schedule_time_alt'], $_POST['schedule_hours'], $_POST['schedule_minutes'] );
		$data = array(
			'csr_price'		=>	$_POST['selling_price_csr'],
			'price_type'	=>	$_POST['price_type'],
			'create_date'	=>	gmdate('Y-m-d H:i'),
			'start_date'	=>	$schedule_time,
			'status'		=>	$status,
		);
		$insert = $wpdb->insert($tableScheduler, $data);
		if( $insert ){
			if( $_POST['price_type'] == 'prompt' ){
				$lastid = $wpdb->insert_id;
				$getOldActive = $wpdb->get_results("SELECT * FROM $tableScheduler WHERE status='active' AND id!=$lastid");
				if( $getOldActive ){
					foreach( $getOldActive as $oldActive ){
						$dataActive = array( 'status'	=>	'overwritten' );
						$whereActive = array( 'id'	=>	$oldActive->id );
						$updateActive = $wpdb->update($tableScheduler, $dataActive, $whereActive);
					}
				}

				$selling_price_csr = ( !empty( $_POST['selling_price_csr'] ) ) ? $_POST['selling_price_csr'] : 0.025;
				update_option( 'selling_price_csr', $selling_price_csr );
				update_option( 'selling_price_csr25', $selling_price_csr );
			}
			// $out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path('csr-scheduler') ) );
			//$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( get_page_by_path('csr-price-scheduler') ) );
			$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'redirect_url'	=> get_permalink( 5631 ) );
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_csr_schedular_script','cip_csr_schedular_script_cb');
add_action('wp_ajax_nopriv_csr_schedular_script','cip_csr_schedular_script_cb');
function cip_csr_schedular_script_cb(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableScheduler = $wpdb->prefix.'csr_scheduler';
	if( isset( $_GET['cronmicro'] ) && str_rot13( $_REQUEST['cronmicro'] ) === 'CIPcsr_schedularCIP'  ){ //PVCpfe_fpurqhynePVC
		$getSchedulars = $wpdb->get_results("SELECT * FROM $tableScheduler WHERE price_type='scheduled' AND status='pending'");
		if( $getSchedulars ){
			foreach( $getSchedulars as $getSchedular ){
				$start_date = "";
				$current_date = DateTime::createFromFormat( 'Y-m-d H:i', gmdate('Y-m-d H:i') );
				try{
					$start_date = DateTime::createFromFormat( 'Y-m-d H:i', $getSchedular->start_date );
				}catch (\Throwable $th){
				}
				if( !empty( $start_date ) ){
					if( $current_date >= $start_date ){

						$dataActive = array( 'status'	=>	'overwritten' );
						$whereActive = array( 'status'	=>	'active' );
						$updateActive = $wpdb->update($tableScheduler, $dataActive, $whereActive);
						$data = array('status'	=>	'active');
						$where = array('id'	=>	$getSchedular->id);
						$update = $wpdb->update($tableScheduler, $data, $where);
						if( $update ){
							update_option( 'selling_price_csr', $getSchedular->csr_price );
							update_option( 'selling_price_csr25', $getSchedular->csr_price );
						}
					}
				}
			}
		}
	}
	// echo gmdate('Y-m-d H:i');
	// echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_schedular_remover','cip_schedular_remover_callback');
function cip_schedular_remover_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyPendingSchedularDeleteyX_' ) ){
		global $wpdb;
		$tableScheduler = $wpdb->prefix.'csr_scheduler';
		$getSingleSchedular = $wpdb->get_row("SELECT id FROM $tableScheduler WHERE id = ".$_POST['thisid']." AND status = 'pending'");
		if( $getSingleSchedular ){
			$where = [ 'id' => $_POST['thisid'] ];
			$deleting = $wpdb->delete( $tableScheduler, $where );
			$out = array( "error" => 0,'msg' => __('Record Deleted',CIP_TXTDOMAIN) );
		}else{
			$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_retirement_setting_act','cip_retirement_setting_act_callback');
function cip_retirement_setting_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxRetirement_SettingxCIP_' ) ){
		global $wpdb;
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
		$getRetirementSetting = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE email = '".$refAccount."' ");
		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		//company name add,update code
		$company_name = $_POST['company_name'];
		$company_name_toggle = ( isset( $_POST['company_name_toggle'] ) && $_POST['company_name_toggle'] == 1 ) ? $_POST['company_name_toggle'] : 0;
		if( $getRetirementSetting ){ //update
			$where = [ 'id' => $getRetirementSetting->id ];
			$data = array(
				'company_name'			=>	$company_name,
				'company_name_toggle'	=>	$company_name_toggle,
				'last_update'			=>	date_i18n('Y-m-d H:i:s'),
			);
			$update = $wpdb->update( $tableRetirementSetting, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Profile update successfully',CIP_TXTDOMAIN) );
			}
		}else{ //insert
			$data = array(
				'email'					=>	$refAccount,
				'company_name'			=>	$company_name,
				'company_name_toggle'	=>	$company_name_toggle,
				'last_update'			=>	date_i18n('Y-m-d H:i:s'),
			);
			$insert = $wpdb->insert( $tableRetirementSetting, $data );
			if( $insert ){
				$out = array( "error" => 0,'msg' => __('Profile update successfully',CIP_TXTDOMAIN) );
			}
		}
		//member url, member logo add,update script
		$getRetirementSetting = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE email = '".$refAccount."' ");
		if( $getRetirementSetting->status != 2 ){ //only execute if not in review state
			$savedMemberUrl = $_POST['member_url'];
			if( $_POST['member_url'] == "" ){
				$savedMemberUrl = $getRetirementSetting->member_url;
			}
			$savedMemberLogo = $_FILES['member_logo']['tmp_name'];
			if( $_FILES['member_logo']['tmp_name'] == "" ){
				$savedMemberLogo = $getRetirementSetting->member_logo;
			}
			if( $savedMemberUrl == "" && $savedMemberLogo == "" ){
				//nothing to do
			}else{
				if( $getRetirementSetting ){ //update
					$where = [ 'id' => $getRetirementSetting->id ];

					if( $getRetirementSetting->status == 0 || $getRetirementSetting->status == 1 ){


						$isGotoUpdate = true;
						if( $getRetirementSetting->status == 1 ){
							if( $_POST['member_url'] != $getRetirementSetting->member_url || $_FILES['member_logo']['tmp_name'] != "" ){
								$isGotoUpdate = true;
							}else{
								$isGotoUpdate = false;
							}
						}
						if( $getRetirementSetting->status == 0 ){
							if( $_POST['member_url'] != $getRetirementSetting->member_url || $_FILES['member_logo']['tmp_name'] != "" ){
								$isGotoUpdate = true;
							}else{
								$isGotoUpdate = false;
							}
						}

						if( $isGotoUpdate ){
							$savedLogo = $getRetirementSetting->member_logo;
							$savedUrl = $getRetirementSetting->member_url;


							if( !empty( $_POST['member_url'] ) && !filter_var($_POST['member_url'], FILTER_VALIDATE_URL) ){
								$out = array( "error" => 1,'msg' => __('Company url is not a valid format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}

							if( ( $_POST['member_url'] != "" && $savedLogo != "" ) || ( $_POST['member_url'] != "" && $_FILES['member_logo']['tmp_name'] != "" ) ){

								$isNewUploadLogo = false;
								if(!empty($_FILES["member_logo"]["name"]) && is_uploaded_file($_FILES['member_logo']['tmp_name']) ){

									$fileName = basename($_FILES["member_logo"]["name"]);

									$fileinfo = @getimagesize($_FILES["member_logo"]["tmp_name"]);

									$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
									$width = $fileinfo[0];
									$height = $fileinfo[1];

									$allowTypes = array('jpg','png','jpeg');


									if(!in_array($fileType, $allowTypes)){
										$out = array( "error" => 1,'msg' => __('Choose valid logo file',CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}else if ($width > "250" || $height > "250"){
										$out = array( "error" => 1,'msg' => __('Logo size should be within 250*250px',CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}else if (($_FILES["member_logo"]["size"] > 100000)){
										$out = array( "error" => 1,'msg' => __('Logo size exceeds 100KB',CIP_TXTDOMAIN) );
										echo wp_json_encode( $out );
										exit;
									}else{
										$image = $_FILES['member_logo']['tmp_name'];
										$member_logo = file_get_contents($_FILES['member_logo']['tmp_name']);
										$isNewUploadLogo = true;
									}
								}

								$data = array(
									'last_update'			=>	date_i18n('Y-m-d H:i:s'),
								);

								if( $getRetirementSetting->status != 2 ){

									$data = wp_parse_args( ['member_url' => $_POST['member_url']], $data );
									$rejection_msg = "";
									$status = 2;

									if( $isNewUploadLogo ){
										$data = wp_parse_args( ['member_logo' => $member_logo], $data );
										$rejection_msg = "";
										$status = 2;
									}
									$data = wp_parse_args( ['status' => $status], $data );
									$data = wp_parse_args( ['rejection_msg' => $rejection_msg], $data );
									$logs = sprintf( __('%s update company url or logo, send to review at %s', CIP_TXTDOMAIN), $refAccount, date_i18n('d/m/Y H:i A') );
									create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
								}
								$update = $wpdb->update( $tableRetirementSetting, $data, $where );
								if( $update ){
									$out = array( "error" => 0,'msg' => __('Profile update successfully.',CIP_TXTDOMAIN) );
								}


							}else{
								$out = array( "error" => 1,'msg' => __('Company url & logo are both required.',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}
					}

				}else{ //insert

					if( ( $_POST['member_url'] != "" && $_FILES['member_logo']['tmp_name'] != "" ) ){
						if( !empty( $_POST['member_url'] ) && !filter_var($_POST['member_url'], FILTER_VALIDATE_URL) ){
							$out = array( "error" => 1,'msg' => __('Company url is not a valid format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$isNewUploadLogo = false;
						if(!empty($_FILES["member_logo"]["name"]) && is_uploaded_file($_FILES['member_logo']['tmp_name']) ){

							$fileName = basename($_FILES["member_logo"]["name"]);

							$fileinfo = @getimagesize($_FILES["member_logo"]["tmp_name"]);

							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$width = $fileinfo[0];
							$height = $fileinfo[1];

							$allowTypes = array('jpg','png','jpeg');


							if(!in_array($fileType, $allowTypes)){
								$out = array( "error" => 1,'msg' => __('Choose valid logo file',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if ($width > "250" || $height > "250"){
								$out = array( "error" => 1,'msg' => __('Logo size should be within 250*250px',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["member_logo"]["size"] > 100000)){
								$out = array( "error" => 1,'msg' => __('Logo size exceeds 100KB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else{
								$image = $_FILES['member_logo']['tmp_name'];
								$member_logo = file_get_contents($_FILES['member_logo']['tmp_name']);
								$isNewUploadLogo = true;
							}
						}

						if( $isNewUploadLogo ){

							$data = array(
								'email'					=>	$refAccount,
								'member_url'			=>	$_POST['member_url'],
								'member_logo'			=>	$member_logo,
								'status'				=>	2,
								'last_update'			=>	date_i18n('Y-m-d H:i:s'),
							);
							$insert = $wpdb->insert( $tableRetirementSetting, $data );
							if( $insert ){
								$logs = sprintf( __('%s update company url or logo, send to review as %s', CIP_TXTDOMAIN), $refAccount, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
								$out = array( "error" => 0,'msg' => __('Profile update successfully.',CIP_TXTDOMAIN) );
							}

						}else{
							$out = array( "error" => 1,'msg' => __('Company logo required.',CIP_TXTDOMAIN) );
						}


					}else{
						$out = array( "error" => 1,'msg' => __('Company url & logo are both required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}

				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//includes shortcodes file
include 'includes/shortcodes.php';
include 'includes/support-ticket-api.php';
include 'includes/refer_script.php';
include 'includes/cip-bst-ajax.php';
include 'includes/Converter.php';
include 'php-ecrecover/autoload.php';
include 'addressValidator/vendor/autoload.php';
include 'includes/member_assistant.php';
// require_once 'google2fa/vendor/autoload.php'; //5753 code
use \PsychoB\Ethereum\AddressValidator;
//custom endpoint API
add_action( 'init', 'csrnow_add_custom_api_endpoint' );
function csrnow_add_custom_api_endpoint() {
	add_rewrite_endpoint( 'API', EP_ALL );
}
add_filter('request', 'csrnow_api_set_queryvar');
function csrnow_api_set_queryvar($vars) {
	if ( isset($vars['API']) ) {
		$vars['API'] = 'apicallback';
	}
	return $vars;
}
add_action( 'template_redirect', 'csrnow_api_template_redirect' );
function csrnow_api_template_redirect() {
	switch (get_query_var('API')) {
		case 'apicallback':
			if( isset( $_GET['q'] ) && $_GET['q'] == 'totalcoins' ){
				echo 10000000000;
			}else{
				echo 'Something went wrong.';
			}
			exit;
	}
}
add_action('wp_ajax_partial_export_act','partial_export_act_callback');

function partial_export_act_callback(){

	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );



	if( wp_verify_nonce( $_POST['_micro'],'CIP_partial_export_CIP' ) ){

		global $defaultColumnsArr;

		global $wpdb;

		$tableName = $wpdb->prefix.'token_holder';

		$needColumns = array('reference', 'username', 'email', 'eth_address', 'pool_ref', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'corp_approved');

		$columnOrders = (array)get_option('cip_sm_column_order');

		$columnsLabelArr = (array)get_option('cip_sm_column_labels');

		$columnsArr = array();

		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){

			foreach( $columnOrders as $columnOrder ){

				if( in_array( $columnOrder, $needColumns ) ){

					$columnsArr[$columnOrder] = $defaultColumnsArr[$columnOrder];

				}

			}

		}

		if( empty( $columnsArr ) ){

			$columnsArr = $defaultColumnsArr;

		}

		if( isset( $_POST['is_export_process'] ) && $_POST['is_export_process'] == 1 ){



			global $wpdb;

			$sheetCounter = 0;



			//select query

			$filter_qry = "";

			foreach( $needColumns as $needColumn ){

				if( isset( $_POST[ $needColumn ] ) && !empty( $_POST[ $needColumn ] ) ){


					if( $needColumn == 'pool_ref' || $needColumn == 'corp_approved' || $needColumn == 'username' ){
						$filter_data = array_filter($_POST[ $needColumn ]);
						if(!empty($filter_data)){
							$filter_qry .= ' AND `'.$needColumn.'` IN ("' . implode('", "', $filter_data) . '")';
						}
					}else{

						$filter_qry .= " AND `$needColumn` = '" . $_POST[ $needColumn ] . "'";

					}

				}

			}

			if( !empty( $filter_qry ) ){

				$getTHsData = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry");

			}





			$exportFile = fopen('php://memory', 'w');

			$columnHeader = array( 'reference', 'eth_address', 'occurs_times', 'csr_amount_initial', 'csramount_by_ethaddress', 'csr_amount_issued', 'amount_due', 'username', 'csramount_byusername', 'occurs_times_user', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', '_user_status', 'kyc_status', 'pool_ref', 'approvedkyc', 'corp_approved', 'notes_external', 'notes_internal', 'Position', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'note_1', 'note_2', 'note_3', 'note_4', 'note_5', 'note_6', 'note_7', 'note_8', 'note_9', 'note_10', 'imported_by', 'import_at', 'last_update_at', 'saved_amount', 'saving_date', 'saving_start_date', 'saving_interest', 'saving_periods', 'saving_state', 'sign_verify', 'transhash', 'contract_address', 'receiver_address', 'ma_enabled', 'token' );


			fputcsv($exportFile, $columnHeader);



			if( $getTHsData ){

				foreach( $getTHsData as $getTHData ){



					$redemption_date_formatted = "";

					if( $getTHData->redemption_date ){

						$formattedRDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->redemption_date );

						if( $formattedRDate ){

							$redemption_date_formatted = $formattedRDate->format('d/m/Y');

						}

					}

					$claim_date_formatted = "";

					if( $getTHData->claim_date ){

						$formattedCDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->claim_date );

						if( $formattedCDate ){

							$claim_date_formatted = $formattedCDate->format('d/m/Y');

						}

					}



					$rowData = array( $getTHData->reference, $getTHData->eth_address, $getTHData->occurs_times, $getTHData->csr_amount_initial, $getTHData->csramount_by_ethaddress, $getTHData->csr_amount_issued, $getTHData->amount_due, $getTHData->username, $getTHData->csramount_byusername, $getTHData->occurs_times_user, $getTHData->first_name, $getTHData->last_name, $redemption_date_formatted, $claim_date_formatted, $getTHData->email, $getTHData->_user_status, $getTHData->kyc_status, $getTHData->pool_ref, $getTHData->approvedkyc, $getTHData->corp_approved, $getTHData->notes_external, $getTHData->notes_internal, $getTHData->position, $getTHData->text_1, $getTHData->text_2, $getTHData->text_3, $getTHData->text_4, $getTHData->text_5, $getTHData->text_6, $getTHData->text_7, $getTHData->text_8, $getTHData->text_9, $getTHData->text_10, $getTHData->date_1, $getTHData->date_2, $getTHData->date_3, $getTHData->date_4, $getTHData->date_5, $getTHData->date_6, $getTHData->date_7, $getTHData->date_8, $getTHData->date_9, $getTHData->date_10, $getTHData->int_1, $getTHData->int_2, $getTHData->int_3, $getTHData->int_4, $getTHData->int_5, $getTHData->int_6, $getTHData->int_7, $getTHData->int_8, $getTHData->int_9, $getTHData->int_10, $getTHData->note_1, $getTHData->note_2, $getTHData->note_3, $getTHData->note_4, $getTHData->note_5, $getTHData->note_6, $getTHData->note_7, $getTHData->note_8, $getTHData->note_9, $getTHData->note_10, $getTHData->imported_by, $getTHData->import_at, $getTHData->last_update_at, $getTHData->saved_amount, $getTHData->saving_date, $getTHData->saving_start_date, $getTHData->saving_interest, $getTHData->saving_periods, $getTHData->saving_state, $getTHData->sign_verify, $getTHData->transhash, $getTHData->contract_address, $getTHData->receiver_address, $getTHData->ma_enabled, $getTHData->token);

					fputcsv($exportFile, $rowData);

					$excelRow++;

				}

			}



			$current_user = wp_get_current_user();

			$logs = sprintf( __('Partial Export Holder Data by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );

			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );



			fseek($exportFile, 0);

			$file_name = 'CSRHolder-'.date_i18n('d-m-Y H-i-s');

			header('content-type:application/csv;charset=UTF-8');

			header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');

			fpassthru($exportFile);

			fclose($exportFile);

			exit;



		}else{

			$foundCount = 0;

			//select query

			$filter_qry = "";

			foreach( $needColumns as $needColumn ){

				if( isset( $_POST[ $needColumn ] ) && !empty( $_POST[ $needColumn ] ) ){


					if( $needColumn == 'pool_ref' || $needColumn == 'corp_approved' || $needColumn == 'username' ){
						$filter_data = array_filter($_POST[ $needColumn ]);
						if(!empty($filter_data)){
							$filter_qry .= ' AND `'.$needColumn.'` IN ("' . implode('", "', $filter_data) . '")';
						}

					}else{

						$filter_qry .= " AND `$needColumn` = '" . $_POST[ $needColumn ] . "'";

					}

				}

			}

			if( !empty( $filter_qry ) ){

				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry");

			}

			$html = "";

			ob_start();

			?>

			<table id="partial_filtered_table"  data-filter-control="false" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered">

			<thead>

			<tr>

				<th data-field="id" class="id" data-switchable="false"><?php _e('Id',CIP_TXTDOMAIN); ?></th>

				<?php

				if( $columnsArr ){

					foreach( $columnsArr as $columnKey => $columnsVal ){

						$filter_attr = 'data-filter-control="input"';

						if( $columnKey == '_user_status' || $columnKey == 'kyc_status' || $columnKey == 'corp_approved' ){

							$filter_attr = 'data-filter-control="select" class="status" data-filter-custom-search="BsTableFilterStatus"';

						}

						$cLabel = ( !empty( $columnsLabelArr[ $columnKey ] ) ) ? $columnsLabelArr[ $columnKey ] : $columnsVal;

					?>

					<th data-field="<?php echo $columnKey ?>" data-sortable="true" <?php echo $filter_attr; ?> class="<?php echo $columnKey ?>"><?php echo $cLabel; ?></th>

					<?php

					}

				}

				?>

			</tr>

			</thead>

			<tbody>

			<?php

			if( $getCurrentMembers ){

				$sno = 1;

				foreach( $getCurrentMembers as $getCurrentMember ){


					$sno++;

					$foundCount++;

				}

			}

			?>

			</tbody>

			</table>

			<?php
			$html .= ob_get_clean();

			$out = array( "error" => 0, 'content' => $html, 'count' => $foundCount, 'filter_qry' => $filter_qry );

		}

		echo wp_json_encode( $out );

		exit;

	}

}
//clear section script
add_action('wp_ajax_partial_clear_act','partial_clear_act_callback');
function partial_clear_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	if( wp_verify_nonce( $_POST['_micro'],'CIP_partial_clear_CIP' ) ){
		global $defaultColumnsArr;
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		$needColumns = array('reference', 'username', 'email', 'eth_address', 'pool_ref', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10');
		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsArr = array();
		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
			foreach( $columnOrders as $columnOrder ){
				if( in_array( $columnOrder, $needColumns ) ){
					$columnsArr[$columnOrder] = $defaultColumnsArr[$columnOrder];
				}
			}
		}
		if( empty( $columnsArr ) ){
			$columnsArr = $defaultColumnsArr;
		}
		if( isset( $_POST['is_clear_process'] ) && $_POST['is_clear_process'] == 1 ){
			global $wpdb;
			//select query
			$filter_qry = "";
			foreach( $needColumns as $needColumn ){
				if( isset( $_POST[ $needColumn ] ) && !empty( $_POST[ $needColumn ] ) ){
					if( $needColumn == 'pool_ref' ){
						$filter_qry .= ' AND `'.$needColumn.'` IN ("' . implode('", "', $_POST[ $needColumn ]) . '")';
					}else{
						$filter_qry .= " AND `$needColumn` = '" . $_POST[ $needColumn ] . "'";
					}
				}
			}
			if( !empty( $filter_qry ) ){
				$deleteTHsData = $wpdb->query("DELETE FROM $tableName WHERE 1 $filter_qry");
				if( $deleteTHsData ){
					$out = array( "error" => 0,'msg' => __('Record(s) cleared.',CIP_TXTDOMAIN), 'content' => '','is_clear' => 1 );
					$current_user = wp_get_current_user();
					$logs = sprintf( __('Cleared Holder Data by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
				}else{
					$out = array( "error" => 1,'msg' => __('Error while clearing.',CIP_TXTDOMAIN) );
				}
			}
		}else{
			$foundCount = 0;
			//select query
			$filter_qry = "";
			foreach( $needColumns as $needColumn ){
				if( isset( $_POST[ $needColumn ] ) && !empty( $_POST[ $needColumn ] ) ){
					if( $needColumn == 'pool_ref' ){
						$filter_qry .= ' AND `'.$needColumn.'` IN ("' . implode('", "', $_POST[ $needColumn ]) . '")';
					}else{
						$filter_qry .= " AND `$needColumn` = '" . $_POST[ $needColumn ] . "'";
					}
				}
			}
			if( !empty( $filter_qry ) ){
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry");
			}
			$html = "";
			ob_start();
			?>
			<table id="partial_filtered_table"  data-filter-control="false" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" class="table table-bordered">
			<thead>
			<tr>
				<th data-field="id" class="id" data-switchable="false"><?php _e('Id',CIP_TXTDOMAIN); ?></th>
				<?php
				if( $columnsArr ){
					foreach( $columnsArr as $columnKey => $columnsVal ){
						$filter_attr = 'data-filter-control="input"';
						if( $columnKey == '_user_status' || $columnKey == 'kyc_status' || $columnKey == 'corp_approved' ){
							$filter_attr = 'data-filter-control="select" class="status" data-filter-custom-search="BsTableFilterStatus"';
						}
						$cLabel = ( !empty( $columnsLabelArr[ $columnKey ] ) ) ? $columnsLabelArr[ $columnKey ] : $columnsVal;
					?>
					<th data-field="<?php echo $columnKey ?>" data-sortable="true" <?php echo $filter_attr; ?> class="<?php echo $columnKey ?>"><?php echo $cLabel; ?></th>
					<?php
					}
				}
				?>
			</tr>
			</thead>
			<tbody>
			<?php
			if( $getCurrentMembers ){
				$sno = 1;
				foreach( $getCurrentMembers as $getCurrentMember ){

					if( $columnsArr ){
						?><tr>
						<td><?php echo $sno; ?></td>
						<?php
						foreach( $columnsArr as $columnKey => $columnsVal ){
							if( $columnKey == 'eth_address_status' ){
								$verified = false;
								$tableSign = $wpdb->prefix.'eth_sign_validate';
								$getSignedData = $wpdb->get_row("SELECT * FROM $tableSign WHERE email = '".$getCurrentMember->email."' AND eth_address = '".strtolower( $getCurrentMember->eth_address )."' AND verify_status = 1 ");
								if( $getSignedData ){
									$verified = true;
								}
								$columnsDataVal = ( $verified ) ? __('Verified',CIP_TXTDOMAIN) : __('Not verified',CIP_TXTDOMAIN);
							}else{
								$columnsDataVal = $getCurrentMember->$columnKey;
								if( $columnKey == 'eth_address' ){
									if( !empty( $columnsDataVal ) ){
										$columnsDataValMask = substr($columnsDataVal, 0, 6) . '...' . substr($columnsDataVal, -6);
										$columnsDataVal = '<a href="https://etherscan.io/address/'. $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataValMask . '</a>';
									}else{
										$columnsDataVal = '—';
									}
								}
							}
							?>
							<td><?php echo $columnsDataVal; ?></td>
							<?php
						}
						?></tr><?php
					}
					$sno++;
					$foundCount++;
				}
			}
			?>
			</tbody>
			</table>
			<?php
			$html .= ob_get_clean();
			$out = array( "error" => 0, 'content' => $html, 'count' => $foundCount , 'is_clear' => 0 );
		}
		echo wp_json_encode( $out );
		exit;
	}
}
add_action( 'wp_ajax_create_member_act', 'cip_create_member_act_callback' );
function cip_create_member_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPcreate_memberCIPY_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) || current_user_can( 'member_assistant' ) ) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		if( !empty( $_POST['member_username'] ) && !empty( $_POST['member_email'] ) ){
			if( !filter_var( $_POST['member_email'], FILTER_VALIDATE_EMAIL) ){
				$out = array( "error" => 1,'msg' => __('Invalid email address',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$getUsernameData = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE username = '".$_POST['member_username']."'");
			$getEmailData = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE email = '".$_POST['member_email']."' ");
			if( $getUsernameData ){
				$out = array( "error" => 1,'msg' => __('Username in use, please choose another username.',CIP_TXTDOMAIN) );
			}else if( $getEmailData ){
				$out = array( "error" => 1,'msg' => __('Email address in use, please choose another email address.',CIP_TXTDOMAIN) );
			}else{
				$insert = $wpdb->insert( $tableName, ['username' => $_POST['member_username'], 'email' => $_POST['member_email'] ]);
				if( $insert ){
					$insert_id = $wpdb->insert_id;
					$redirect_url = add_query_arg( array(
						'action' => 'edit',
						'id' => $insert_id,
					), get_permalink( $_POST['pageid'] ) );
					if( current_user_can( 'member_assistant' ) ){
						$out = array( "error" => 0,'msg' => __('Account created',CIP_TXTDOMAIN), 'redirect_url' => '' );
					}else{
						$out = array( "error" => 0,'msg' => __('Member created',CIP_TXTDOMAIN), 'redirect_url' => $redirect_url );
					}
					$tableLog = $wpdb->prefix.'cip_logs';
					$user = wp_get_current_user();
					$userData = get_user_by( 'id', $user->ID );
					$refAccount = $userData->user_email;
					$logData = array(
						'user_id'	=>	0,
						'user_type'	=>	'MAs',
						'log_type'	=>	'member_create',
						'logs'		=>	sprintf( __('%s created account %s with email %s at %s', CIP_TXTDOMAIN), $refAccount, $_POST['member_username'], $_POST['member_email'], date_i18n('Y-m-d H:i:s') ),
						'_date'		=>	date_i18n('Y-m-d H:i:s'),
					);
					$log_insert = $wpdb->insert( $tableLog, $logData );
				}else{
					$out = array( "error" => 1,'msg' => __('Member not created',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_username_fetch_act', 'cip_username_fetch_act_callback' );
function cip_username_fetch_act_callback(){
	global $wpdb;
	$out = array();
	$tableName = $wpdb->prefix.'token_holder';
	$get_usernames = $wpdb->get_results("SELECT DISTINCT username FROM $tableName WHERE `username` like '".$_REQUEST['search']."%'");
	if( $get_usernames ){
		foreach( $get_usernames as $get_username ){
			$out[] = array(
				'id'	=>	$get_username->username,
				'text'	=>	$get_username->username,
			);
		}
	}
	echo wp_json_encode( array( 'results' => $out ) );
	exit;
}
function cip_get_circulation_balance( $ethaddress = '' ){
	$csr_amount = '-';
	if( !empty( $ethaddress ) ){

		$contractaddress = get_option('csr_wallet_api_mode_live_tkn');
		$apikey = get_option('csr_wallet_api_mode_live_api');
		$endpoint = 'https://api.etherscan.io/api';
		$etherscanUrl = add_query_arg( array(
			'module' 			=> 'account',
			'action' 			=> 'tokenbalance',
			'contractaddress'	=>	$contractaddress,
			'address'			=>	$ethaddress,
			'tag'				=>	'latest',
			'apikey'			=>	$apikey
		), $endpoint );

		$request = wp_remote_get( $etherscanUrl );
		if( is_wp_error( $request ) ) {
			return $csr_amount;
		}
		$body = wp_remote_retrieve_body( $request );
		$data = json_decode( $body, true );
		if( isset( $data['result'] ) ){
			$csr_amount = $data['result'];
			$converter = new Bezhanov\Ethereum\Converter();
			$value = $converter->fromWei( $csr_amount , 'ether');
			if( $value > 0 ){
				// $csr_amount = rtrim( $value, 0 );
				$csr_amount = $value;
			}
		}
	}
	return $csr_amount;
}
function cip_get_circulation_balance_csr25( $ethaddress = '' ){
	$csr_amount = '-';
	if( !empty( $ethaddress ) ){

		$contractaddress = get_option('csr25_wallet_api_mode_live_tkn');
		$apikey = get_option('csr25_wallet_api_mode_live_api');
		$endpoint = 'https://api.etherscan.io/api';
		$etherscanUrl = add_query_arg( array(
			'module' 			=> 'account',
			'action' 			=> 'tokenbalance',
			'contractaddress'	=>	$contractaddress,
			'address'			=>	$ethaddress,
			'tag'				=>	'latest',
			'apikey'			=>	$apikey
		), $endpoint );

		$request = wp_remote_get( $etherscanUrl );
		if( is_wp_error( $request ) ) {
			return $csr_amount;
		}
		$body = wp_remote_retrieve_body( $request );
		$data = json_decode( $body, true );
		if( isset( $data['result'] ) ){
			$csr_amount = $data['result'];
			$converter = new Bezhanov\Ethereum\Converter();
			$value = $converter->fromWei( $csr_amount , 'ether');
			if( $value > 0 ){
				// $csr_amount = rtrim( $value, 0 );
				$csr_amount = $value;
			}
		}
	}
	return $csr_amount;
}
add_action( 'wp_ajax_create_smcirculation_act', 'cip_create_smcirculation_act_callback' );
function cip_create_smcirculation_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPcreate_circulationCIPXy_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableCirculationData = $wpdb->prefix.'circulation_data';
		if( !empty( $_POST['description'] ) && !empty( $_POST['address'] ) && !empty( $_POST['token'] ) ){
			$getCirculation = $wpdb->get_row("SELECT * FROM $tableCirculationData WHERE `address` = '".$_POST['address']."'");
			if( $getCirculation ){
				$out = array( "error" => 1,'msg' => __('Wallet already added',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$insert = $wpdb->insert( $tableCirculationData, ['description' => $_POST['description'], 'address' => $_POST['address'], 'token' => $_POST['token'], 'status' => 1, 'created_date' => date_i18n( 'Y-m-d H:i:s' ) ]);
			if( $insert ){
				$out = array( "error" => 0,'msg' => __('Wallet added successfully.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Wallet adding failed.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_get_circulation_data_action', 'cip_get_circulation_data_action_callback' );
function cip_get_circulation_data_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCirculationData = $wpdb->prefix.'circulation_data';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$circulation_id = preg_replace(sprintf('/%s/', 'CirculationsData' ), '', $decryptedId_raw);
		$getData = $wpdb->get_row("SELECT * FROM $tableCirculationData WHERE 1 AND id = ".$circulation_id."");
		if( $getData ){
			ob_start();
			?>
			<form class="edit_circulationModal_frm" id="edit_circulationModal_frm" name="edit_circulationModal_frm">
				<div class="form-group">
					<h5><?php _e('Edit record', CIP_TXTDOMAIN); ?></h5>
				</div>
				<div class="form-group">
					<input type="text" class="form-control" id="description" name="description" placeholder="<?php _e('Description *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->description; ?>" />
				</div>
				<div class="form-group">
					<input type="text" class="form-control" id="address" name="address" placeholder="<?php _e('Address *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->address; ?>" />
				</div>
				<div class="form-group">
					<select class="form-control" id="token" name="token">
						<option value="">Please select Token</option>
						<option value="CSR" <?=($getData->token == 'CSR') ? 'selected' : '' ;?>>CSR</option>
						<option value="CSR25" <?=($getData->token == 'CSR25') ? 'selected' : '' ;?>>CSR25</option>
					</select>
				</div>
				<button type="submit" class="btn btn-secondary"><?php _e('Update', CIP_TXTDOMAIN); ?></button>
				<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
				<input type="hidden" name="action" value="update_smcirculation_act" />
				<input type="hidden" name="circulation_id" value="<?php echo $_POST['thisId']; ?>" />
				<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YxCIPEdit_circulationCIPXy_'); ?>" />
				<p><span class="form_response"></span></p>
			</form>
			<?php
			$html = ob_get_clean();
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_update_smcirculation_act', 'cip_update_smcirculation_act_callback' );
function cip_update_smcirculation_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCirculationData = $wpdb->prefix.'circulation_data';
		$decryptedId_raw = base64_decode( $_POST['circulation_id'] );
		$circulation_id = preg_replace(sprintf('/%s/', 'CirculationsData' ), '', $decryptedId_raw);
		$getCirculation = $wpdb->get_row("SELECT * FROM $tableCirculationData WHERE id != ".$circulation_id." AND `address` = '".$_POST['address']."'");
		if( $getCirculation ){
			$out = array( "error" => 1,'msg' => __('Wallet already added',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$getData = $wpdb->get_row("SELECT * FROM $tableCirculationData WHERE 1 AND id = ".$circulation_id."");
		if( $getData ){
			$data = [ 'description' => $_POST['description'], 'address' => $_POST['address'], 'token' => $_POST['token'], 'created_date' => date_i18n( 'Y-m-d H:i:s' ) ];
			$where = [ 'id'	=> $circulation_id ];
			$update = $wpdb->update( $tableCirculationData, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Record updated successfully.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Update failed.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_delete_smcirculation_act', 'cip_delete_smcirculation_act_callback' );
function cip_delete_smcirculation_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCirculationData = $wpdb->prefix.'circulation_data';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$circulation_id = preg_replace(sprintf('/%s/', 'CirculationsData' ), '', $decryptedId_raw);
		$getData = $wpdb->get_row("SELECT * FROM $tableCirculationData WHERE 1 AND id = ".$circulation_id."");
		if( $getData ){
			$where = [ 'id'	=> $circulation_id ];
			$delete = $wpdb->delete( $tableCirculationData, $where );
			if( $delete ){
				$out = array( "error" => 0,'msg' => __('Circulation deleted successfully.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('delete failed.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_filter( 'gform_countries', 'cipBuyProductFormRemoveCountry', 99 );
function cipBuyProductFormRemoveCountry( $countries ){
	$newCountries = array();
	if( is_page( 4250 ) ){
		$cipDisabledCountries = get_option( 'cipDisabledCountries' );
		$removeCountriesList = maybe_unserialize( $cipDisabledCountries );
		/* $removeCountriesList = [
			'Afghanistan',
			'American Samoa',
			'Angola',
			'Bahamas',
			'Barbados',
			'Belarus',
			'Bosnia and Herzegovina',
			'Botswana',
			'Burundi',
			'Cambodia',
			'Cabo Verde',
			'Cayman Islands',
			'Central African Republic',
			'Chad',
			'China',
			'Congo',
			'Congo, Democratic Republic of the',
			'Côte d\'Ivoire',
			'Cuba',
			'Korea, Democratic People\'s Republic of',
			'Egypt',
			'Equatorial Guinea',
			'Eritrea',
			'Ethiopia',
			'Fiji',
			'Ghana',
			'Guam',
			'Guinea',
			'Guinea-Bissau',
			'Guyana',
			'Haiti',
			'Iran',
			'Iraq',
			'Jamaica',
// 			'Kenya',
			'Lao People\'s Democratic Republic',
			'Lebanon',
			'Liberia',
			'Libya',
			'Mali',
			'Mauritius',
			'Moldova',
			'Mongolia',
			'Montenegro',
			'Mozambique',
			'Myanmar',
			'Nicaragua',
			'Nigeria',
			'Oman',
			'Pakistan',
			'Palau',
			'Palestine, State of',
			'Panama',
			'Papua New Guinea',
			'Puerto Rico',
			'Russian Federation',
			'Samoa',
			'Saudi Arabia',
			'Serbia',
//			'Seychelles',
			'Sierra Leone',
			'Somalia',
			'Sri Lanka',
			'Sudan',
			'Syria Arab Republic',
			'Tanzania',
			'Tanzania, the United Republic of',
			'Trinidad and Tobago',
// 			'Tunisia',
			'Türkiye',
// 			'Uganda',
			'Vanuatu',
			'Venezuela',
			'Virgin Islands, U.S.',
			'Yemen',
			'Zimbabwe',
		]; */
		foreach( $countries as $country ){
			if( !in_array( $country, $removeCountriesList ) ){
				$newCountries[] = $country;
			}
		}
	}else{
		$newCountries = $countries;
	}
    return $newCountries;
}
add_action( 'wp_ajax_cip_approved_logourl_act', 'cip_approved_logourl_act_callback' );
function cip_approved_logourl_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyApprovedLogoUrlyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', 'CIPLOGOURLAPPROVAL'), '', $decrypted_id_raw);
		$user_id = get_current_user_id();
		$getProfileData = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE id = ".$id." AND status != 1");
		if( $getProfileData ){
			$data = array('status'	=>	1, 'rejection_msg' => '','sa_update_date' => date_i18n( 'Y-m-d H:i:s'), 'last_update' => date_i18n( 'Y-m-d H:i:s'), 'sa_user_id' => $user_id );
			$where = array('id'	=>	$getProfileData->id);
			$update = $wpdb->update( $tableRetirementSetting, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Approved',CIP_TXTDOMAIN) );
				$userData = get_user_by( 'id', $user_id );
				$logs = sprintf( __('Company url or logo approved by SA(%s) at %s', CIP_TXTDOMAIN), $userData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( $user_id, 'profile', '','sa', $logs, true  );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cip_unapprove_logourl_act', 'cip_unapprove_logourl_act_callback' );
function cip_unapprove_logourl_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyUnApproveLogoUrlyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', 'CIPLOGOURLAPPROVAL'), '', $decrypted_id_raw);
		$user_id = get_current_user_id();
		$getProfileData = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE `id` = ".$id." AND `status` = 1");
		if( $getProfileData ){
			$data = array('status'	=>	0, 'rejection_msg' => __('Reject by SA', CIP_TXTDOMAIN),'sa_update_date' => date_i18n( 'Y-m-d H:i:s'), 'last_update' => date_i18n( 'Y-m-d H:i:s'), 'sa_user_id' => $user_id );
			$where = array('id'	=>	$getProfileData->id);
			$update = $wpdb->update( $tableRetirementSetting, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Rejected',CIP_TXTDOMAIN) );
				$userData = get_user_by( 'id', $user_id );
				$logs = sprintf( __('Company url or logo rejected from approved status by SA(%s) at %s', CIP_TXTDOMAIN), $userData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( $user_id, 'profile', '','sa', $logs, true  );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cip_reject_logourl_act', 'cip_reject_logourl_act_callback' );
function cip_reject_logourl_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyRejectLogoUrlyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', 'CIPLOGOURLAPPROVAL'), '', $decrypted_id_raw);
		$user_id = get_current_user_id();
		$getProfileData = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE id = ".$id." AND status != 1");
		if( $getProfileData ){
			$data = array('status'	=>	0, 'rejection_msg' => $_POST['rejectMsg'],'sa_update_date' => date_i18n( 'Y-m-d H:i:s'), 'last_update' => date_i18n( 'Y-m-d H:i:s'), 'sa_user_id' => $user_id );
			$where = array('id'	=>	$getProfileData->id);
			$update = $wpdb->update( $tableRetirementSetting, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Rejected',CIP_TXTDOMAIN) );
				$userData = get_user_by( 'id', $user_id );
				$logs = sprintf( __('Company url or logo rejected with reason(%s) by SA(%s) at %s', CIP_TXTDOMAIN),$_POST['rejectMsg'], $userData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( $user_id, 'profile', '','sa', $logs, true  );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//5077 code
function getOrdinal($number){
	$digit = abs($number) % 10;
	$ext = 'th';
	$ext = ((abs($number) %100 < 21 && abs($number) %100 > 4) ? 'th' : (($digit < 4) ? ($digit < 3) ? ($digit < 2) ? ($digit < 1) ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
	return $number.$ext;
}
function get_amplivo_user_status( $username = '' ){
	$validateData = array(
		'status'	=> '',
		'email'	=>	'',
		'username'	=>	'',
		'sponsor_full_name'	=>	'',
	);
	if( !empty( $username ) ){

		$endpoint = 'https://amplivo.com/api/userstatus/get';
		$request_url = add_query_arg( array(
			'username' 			=> urlencode( $username ),
		), $endpoint );

		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$response_body = wp_remote_retrieve_body( $response );
			$data = json_decode( $response_body );
			if( is_object( $data ) && isset( $data->Status ) ){
				$validateData = array(
					'status'	=> $data->Status,
					'email'	=>	$data->Email,
					'username'	=>	$data->Username,
					'sponsor_full_name'	=>	$data->user_full_name,
				);
			}
		}
	}
	return $validateData;
}
add_action('admin_post_export_distribution_act','cip_export_distribution_act_callback');
function cip_export_distribution_act_callback(){
	global $wpdb;
	$sheetCounter = 0;
	$tableName = $wpdb->prefix . 'token_holder_distribution';
	$tableName = $wpdb->prefix.'token_holder_distribution';
	$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableName SET `append_status` = %d", 1 ) );
	if( $statusUpdate ){
	}
	$getDistributionData = $wpdb->get_results("SELECT * FROM $tableName WHERE `csr_amount_issued` > 0 AND `distribution_status` != 'Security Hold' AND `member_status` = 'active' ");


	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'eth_address', 'csr_amount_issued' );

	fputcsv($exportFile, $columnHeader);
	foreach( $getDistributionData as $getData ){
		$rowData = array( $getData->eth_address, $getData->csr_amount_issued );
		fputcsv($exportFile, $rowData);
		$excelRow++;
	}

	$date = new DateTime(date('Y-m-d'));
	$weekNumber = $date->format("W");
	$current_user = wp_get_current_user();
	$logs = sprintf( __('CSR 10% distributions for week '. $weekNumber .' download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	fseek($exportFile, 0);
	$file_name = 'CSR 10% distributions for week '.$weekNumber;
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}
//5077 code
add_action( 'wp_ajax_append_new_csr_holders_data_act', 'cip_append_new_csr_holders_data_act_callback' );
function cip_append_new_csr_holders_data_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYAppendNew_csr_HoldersDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableTempName = $wpdb->prefix.'token_holder_distribution_temp';
		$tableName = $wpdb->prefix.'token_holder_distribution';
		$tableTokenHolder = $wpdb->prefix.'token_holder';

		if( isset( $_POST['get_append_data'] ) && $_POST['get_append_data'] == 'yes' ){

			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTempName WHERE 1 AND `append_status` != 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );

			$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableName SET `append_status` = %d", 1 ) );
			if( $statusUpdate ){
			}

			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Appending 10% distributions started...',CIP_TXTDOMAIN), 'msg2' => __('Appending 10% distributions started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to append', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset( $_POST['appending_data'] ) && $_POST['appending_data'] == 'yes' ){
			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;

			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCount = 0;

			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableTempName WHERE 1 ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					if( $getTempData->append_status != 1 ){

						$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
						$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
						$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
						$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? str_replace( ',', '', $getTempData->csr_amount_initial) : 0;
						$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
						$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
						$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
						$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
						$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
						$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
						$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
						$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
						$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
						$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';
						$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
						$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
						$pool_reference = ( $getTempData->pool_ref != "" ) ? $getTempData->pool_ref : '';

						$created_formatted = "";
						if( $created ){
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $created);
							if( $formattedCDate ){
								$created_formatted = $formattedCDate->format('d/m/Y');
							}
						}

						if( $csr_amount_initial <= $csr_segmentation ){
							$admNo = $reference.'-000';
							$newAdmNo = ++$admNo;
							$amount_due = $csr_amount_initial;
							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| Pending 10% distribution. |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );

							$text_7 = null;
							if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
								$text_7 = 'Pending';
							}
							$data = array(
								'reference'				=>	wp_strip_all_tags( $newAdmNo ),
								'eth_address'			=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
								'csr_amount_issued'		=>	0,
								'amount_due'			=>	$amount_due,
								'username'				=>	wp_strip_all_tags( $username ),
								'first_name'			=>	wp_strip_all_tags( $first_name ),
								'last_name'				=>	wp_strip_all_tags( $last_name ),
								'redemption_date'		=>	$created_formatted,
								'email'					=>	wp_strip_all_tags( $email ),
								'_user_status'			=>	$member_status,
								// 'kyc_status'			=>	$distribution_status,
								'pool_ref'				=>	$pool_reference,
								'corp_approved'			=>	$corp_approved_10,
								'notes_external'		=>	$notes_external_10,
								'text_7'				=>	$text_7,
								'text_10'				=>	$year_number.'/'.$week_number,
								'text_9'				=>	$source,
								'imported_by'			=>	$import_by,
								'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
							);

							$inserting = $wpdb->insert( $tableTokenHolder, $data );
							if( $inserting ){
								$countSuccess++;
								$user_type = 'sm';
								$log_type = 'weekly_redemptions_append';
								$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
								create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
								$wpdb->update( $tableTempName, array( 'append_status' => 1 ), array( 'id' => $getTempData->id ) );

							}else{
								$error = 1;
								$countError++;
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$csr_amount_pending = $csr_amount_initial;
							$totalNumberWeek = 52;

							$loopCounter = 0;
							for( $i=0; $i < 10; $i++ ){

								$amount_due = $csr_amount_pending / ( 10 - $i );
								$amount_due = ceil( $amount_due );

								if( $i == 0 ){
									$admNo = $reference.'-000';
								}else{
									$admNo = $newAdmNo;
								}
								$newAdmNo = ++$admNo;

								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
									$corp_approved_10 = $distribution_status;
								}else{
									$corp_approved_10 = 'Pending';
								}
								$notes_external_10 = '| Pending 10% distribution. |';
								if( $distribution_status == 'Security Hold' ){
									$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
								}
								$notes_external_10 = notes_trim_pipe( $notes_external_10 );
								if( $week_number > $totalNumberWeek ){
									$week_number = $week_number - $totalNumberWeek;
									$year_number = $year_number + 1;
								}else{
									$year_number = $year_number;
								}
								$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);

								$text_7 = null;
								if( $corp_approved_10 == 'Security Hold' || $corp_approved_10 == 'Hold' ){
									$text_7 = 'Pending';
								}

								$data = array(
									'reference'				=>	wp_strip_all_tags( $newAdmNo ),
									'eth_address'			=>	wp_strip_all_tags( $eth_address ),
									'csr_amount_initial'	=>	wp_strip_all_tags( $csr_amount_initial ),
									'csr_amount_issued'		=>	0,
									'amount_due'			=>	$amount_due,
									'username'				=>	wp_strip_all_tags( $username ),
									'first_name'			=>	wp_strip_all_tags( $first_name ),
									'last_name'				=>	wp_strip_all_tags( $last_name ),
									'redemption_date'		=>	$created_formatted,
									'email'					=>	wp_strip_all_tags( $email ),
									'_user_status'			=>	$member_status,
									// 'kyc_status'			=>	$distribution_status,
									'pool_ref'				=>	$pool_reference,
									'corp_approved'			=>	$corp_approved_10,
									'notes_external'		=>	$notes_external_10,
									'text_7'				=>	$text_7,
									'text_10'				=>	$new_week_number,
									'text_9'				=>	$source,
									'imported_by'			=>	$import_by,
									'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
								);

								$csr_amount_pending = $csr_amount_pending - $amount_due;
								$inserting = $wpdb->insert( $tableTokenHolder, $data );
								if( $inserting ){
									$countSuccess++;
									$loopCounter++;
									$user_type = 'sm';
									$log_type = 'weekly_redemptions_append';
									$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
									create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
								}else{
									$error = 1;
									$countError++;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
									echo wp_json_encode( $out );
									exit;
								}
								// $week_number++;
								$week_number = $week_number + 4;

							}

							if( $loopCounter == 10 ){
								$wpdb->update( $tableTempName, array('append_status' => 1), array( 'id' => $getTempData->id ) );
							}

						}

						$rowDataCount = $getTempData->id;

					}
				}

				if( $_POST['total_paged'] == $_POST['page_id'] ){

					$total_items_user_status = $wpdb->get_var("SELECT COUNT(DISTINCT(`username`)) FROM $tableTempName WHERE 1");
					$per_page = 50;
					$total_paged_user_status = ceil( $total_items_user_status / $per_page );


					$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'yes', 'total_items_user_status' => $total_items_user_status, 'total_paged_user_status' => $total_paged_user_status, 'msg2' => __('User status check & update started...',CIP_TXTDOMAIN), 'totalmsg_user_status' => sprintf( __('%s row\'s to check & update user status', CIP_TXTDOMAIN),$total_items_user_status ), 'test' => "SELECT COUNT(id) FROM $tableTempName WHERE 1 GROUP BY `username`" );

				}else{
					$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'no' );
				}

			}
		}else if( isset( $_POST['appending_data_user_status'] ) && $_POST['appending_data_user_status'] == 'yes' ){
			$per_page = 50;
			$paged = isset( $_POST['page_id_user_status'] ) ? max( 0, intval( $_POST['page_id_user_status'] -1 ) * $per_page ) : 0;

			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowProceed = $paged;

			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableTempName WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					$username = $getTempData->username;
					$member_status = $getTempData->member_status;
					$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableTokenHolder SET `_user_status` = %s WHERE username = %s AND _user_status != 'Security Hold'", $member_status, $username ) );
					if( $statusUpdate ){
						$user_type = 'sm';
						$log_type = 'weekly_appended_status_update';
						$logs = sprintf( __('Member status update, username:%s ,status:%s, pool_ref:%s at %s', CIP_TXTDOMAIN), $username, $member_status, $getTempData->pool_ref,date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
					}
					$rowDataCount++;
					$rowProceed++;
				}
				foreach( $getTempDatas as $getTempData ){
					$username = $getTempData->username;
					$member_status = $getTempData->member_status;
					//only check abandoned
					if( $member_status == 'abandoned' ){
						$expiredDate = 'expired/'.date_i18n('Y-m-d');
						$dataUpdate = array(
							'pool_ref'	=>	$expiredDate
						);
						$dataWhere = array(
							'username'		=>	$username,
							'corp_approved'	=>	'Pending',
							'text_9'		=>	'bonus',
						);
						$poolUpdate = $wpdb->update( $tableTokenHolder, $dataUpdate, $dataWhere );
						if( $poolUpdate ){
							$user_type = 'sm';
							$log_type = 'weekly_appended_status_update';
							$logs = sprintf( __('Pool ref update for abandoned user to %s, username:%s ,corp_approved:Pending, text_9:bonus, pool_ref:%s at %s', CIP_TXTDOMAIN), $expiredDate, $username, $getTempData->pool_ref,date_i18n('d/m/Y H:i:s') );
							create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
						}
					}
				}
			}
			if( $_POST['total_paged_user_status'] == $_POST['page_id_user_status'] ){

				$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: User status checked & updated',CIP_TXTDOMAIN), $rowProceed ), 'isLastPage_user_status' => 'yes', 'test' => "SELECT * FROM $tableTempName WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."" );

				$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
			}else{
				$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: User status checked & updated',CIP_TXTDOMAIN), $rowProceed ), 'isLastPage_user_status' => 'no', 'test' => "SELECT * FROM $tableTempName WHERE 1 GROUP BY `username` ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."" );
			}
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancel_append_process', 'cip_cancel_append_process_callback' );
function cip_cancel_append_process_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYCancelAppendDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder_distribution';
		$tableTempName = $wpdb->prefix.'token_holder_distribution_temp';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('Cancelled',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//5077 code
// add_action('wp_head','clear_csv_array_after_page_load');
function clear_csv_array_after_page_load(){
	$_SESSION['csvArray'] = "";
	unset($_SESSION['csvArray']);
}
//add_action('wp_footer','view_csv_array_after_page_load');
function view_csv_array_after_page_load(){
	echo "<pre>";
	print_r( $_SESSION['csvArray'] );
	echo "</pre>";
}
add_action('wp_ajax_cip_weekly_redemptions_import_act','cip_weekly_redemptions_import_act_callback');
function cip_weekly_redemptions_import_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN), 'msg2' => __('Something went wrong.',CIP_TXTDOMAIN) );
	require 'guzzle/vendor/autoload.php';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMWeeklyRedemptionsImportMSYxCIP_' ) ){
		if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['findPoolFromFile'] ) && $_POST['findPoolFromFile'] == 'yes' ) ){ // fetch pool ref
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			$poolRefPopulate = "";

			if( $fileNameWithoutNumber == 'CSR_redemptions_week' && ctype_digit( $yearWeekextract ) ){
				$year = mb_substr($yearWeekextract, 0, 4);
				$weekNumber = mb_substr($yearWeekextract, 4);
				$poolRefPopulate = sprintf( __('Week-%s-of-%s', CIP_TXTDOMAIN), $weekNumber, $year );
			}else if( $fileNameWithoutNumber == 'CSR_bonus_week' && ctype_digit( $yearWeekextract ) ){
				$year = mb_substr($yearWeekextract, 0, 4);
				$weekNumber = mb_substr($yearWeekextract, 4);
				$poolRefPopulate = sprintf( __('BNS-%s-%s', CIP_TXTDOMAIN), $year, $weekNumber );
			}
			$out = array( "error" => 0,'msg' => 'Pool reference fetched', 'poolRefPopulate' => $poolRefPopulate );
			echo wp_json_encode( $out );
			exit;

		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['fieldmapping'] ) && $_POST['fieldmapping'] == 'yes' ) ){ // field mapping
			global $table_prefix, $wpdb;
			$tableDistribution = $wpdb->prefix.'token_holder_distribution';
			$tableTemp = $wpdb->prefix.'token_holder_distribution_temp';
			$delete = $wpdb->query("TRUNCATE TABLE `".$tableDistribution."`");
			$deleteTemp = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
			$csvFile = $_FILES['th_csv_file']['tmp_name'];

			if( ($handle = fopen($csvFile, 'r')) !== false ){
				$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
   				$total_line = count($file_content) - 1;

				$flag = true;
				$rowDataCount= 0;
				$countError = 0;
				$countSuccess = 0;
				$insertingCount = 1;

				if( str_contains($_POST['pool_reference'], 'BNS') ){
					$poolReferencePattern  = "/^BNS-[0-9]{4}-[0-9]{2}$/i";
				}else{
					$poolReferencePattern  = "/^Week-[0-9]{2}-of-[0-9]{4}$/i";
				}
				if( !preg_match($poolReferencePattern, $_POST['pool_reference']) ){
					$out = array( "error" => 1,'msg' => __('Error : Not valid format of pool reference',CIP_TXTDOMAIN), 'msg2' => __('Error : Not valid format of pool reference',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				while (($rowData = fgetcsv($handle, 0)) !== false) {
					if( $flag ){
						$columnsArr = ['id','username','reference_number','csr_wallet_address','csr_initial','first_name','last_name','created_date','email','source'];
						foreach( $columnsArr as $key => $columnName ){
							if( strtolower($columnName) == strtolower($rowData[ $key] ) ){
								//continue column matched
							}else{
								//error, column not matched
								$out = array( "error" => 1,'msg' => __('Error : column mismatch',CIP_TXTDOMAIN), 'msg2' => __('Error : column mismatch',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}
						$csvdata = array_map('str_getcsv', file( $csvFile ));
						unset( $csvdata[0] );
						if( $csvdata ){
							foreach( $csvdata as $key => $rowData ){
								$rowCounter = $key;
								$username = ( $rowData[ 1 ] != "" ) ? $rowData[ 1 ] : '';
								$reference = ( $rowData[ 2 ] != "" ) ? $rowData[ 2 ] : '';
								$eth_address = ( $rowData[ 3 ] != "" ) ? $rowData[ 3 ] : '';
								$csr_amount_initial = ( $rowData[ 4 ] != "" ) ? str_replace( ',', '', $rowData[ 4 ]) + 0 : '';
								$first_name = ( $rowData[ 5 ] != "" ) ? $rowData[ 5 ] : '';
								$last_name = ( $rowData[ 6 ] != "" ) ? $rowData[ 6 ] : '';
								$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
								$email = ( $rowData[ 8 ] != "" ) ? $rowData[ 8 ] : '';
								$source = ( $rowData[ 9 ] != "" ) ? $rowData[ 9 ] : '';
								$validationError = [];
								if( !filter_var($email, FILTER_VALIDATE_EMAIL) ){
									$rowError = true;
									$validationError[] = __('Email is invalid ',CIP_TXTDOMAIN);
								}
								if( empty( $username ) ){
									$rowError = true;
									$validationError[] = __('Username is empty',CIP_TXTDOMAIN);
								}
								if( $csr_amount_initial == "" && $csr_amount_initial < 0 ){
									$rowError = true;
									$validationError[] = __('csr_initial is empty',CIP_TXTDOMAIN);
								}
								if( !is_int( $csr_amount_initial ) ){
									$rowError = true;
									$validationError[] = __('csr_initial is invalid',CIP_TXTDOMAIN);
								}
								if( empty( $created ) || DateTime::createFromFormat('d/m/Y', $created) === false ){
									$rowError = true;
									$validationError[] = __('Created date is empty or invalid format',CIP_TXTDOMAIN);
								}
								if( $source != 'purchase' && $source != 'bonus' ){
									$rowError = true;
									$validationError[] = __('Source is invalid',CIP_TXTDOMAIN);
								}
								$referencePattern  = "/^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$/i";
								if( empty( $reference ) || !preg_match( $referencePattern, $reference ) ){
									$rowError = true;
									$validationError[] = __('Reference is empty or invalid format',CIP_TXTDOMAIN);
								}
								if( !empty( $eth_address ) && AddressValidator::isValid( $eth_address ) !== AddressValidator::ADDRESS_VALID ){
									$rowError = true;
									$validationError[] = __('Address is invalid',CIP_TXTDOMAIN);
								}
								if( $rowError === true ){
									$log_msg = getOrdinal( $rowCounter ) . ' row :: ' . $reference . ' :: failed : ' . implode(', ', $validationError).'<br/>';
									$countError++;
									$error = 1;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
							}
						}else{
							$out = array( "error" => 1,'msg' => __('Error : empty data in file',CIP_TXTDOMAIN), 'msg2' => __('Error : empty data in file',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$csvdata = array_chunk( $csvdata, 100 );
						$_SESSION['csvArray'] = $csvdata;
						$new_total_line = count( $csvdata );
						$out = array( "error" => 0,'msg' => __('Reference checking started...',CIP_TXTDOMAIN), 'msg2' => __('Reference checking started...',CIP_TXTDOMAIN), 'total_line' => $new_total_line, 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_line ) );
						echo wp_json_encode( $out );
						exit;
						$flag = false;
						continue;
					}
					$rowError = false;
				}
				fclose($handle);
				unlink($csvFile);
			}
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['verification_data'] ) && $_POST['verification_data'] == 'yes' ) ){ // verification process
			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			$week_number = "";
			if( $fileNameWithoutNumber == 'CSR_redemptions_week' && ctype_digit( $yearWeekextract ) ){
				$week_number = mb_substr($yearWeekextract, 4);
			}
			$csr_segmentation = 100;
			if( isset( $_POST['csr_segmentation'] ) && $_POST['csr_segmentation'] >= 10 ){
				$csr_segmentation = $_POST['csr_segmentation'];
			}
			$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
			$total_line = count($file_content) - 1;
			// if( ($handle = fopen($csvFile, 'r')) !== false ){
			if( isset( $_SESSION['csvArray'] ) && !empty( $_SESSION['csvArray'] ) ){

				$csvArray = $_SESSION['csvArray'];
				$splitting_id = $_POST['verification_id'];
				$splittedParts = $csvArray[ $splitting_id ];
				if( !empty( $splittedParts ) && is_array( $splittedParts ) ){
					foreach( $splittedParts as $key => $rowData ){
						$rowCounter = ( $splitting_id * 100 ) + ( $key + 1 );
						$username = ( $rowData[ 1 ] != "" ) ? $rowData[ 1 ] : '';
						$reference = ( $rowData[ 2 ] != "" ) ? $rowData[ 2 ] : '';
						$eth_address = ( $rowData[ 3 ] != "" ) ? $rowData[ 3 ] : '';
						$csr_amount_initial = ( $rowData[ 4 ] != "" ) ? str_replace( ',', '', $rowData[ 4 ]) : 0;
						$first_name = ( $rowData[ 5 ] != "" ) ? $rowData[ 5 ] : '';
						$last_name = ( $rowData[ 6 ] != "" ) ? $rowData[ 6 ] : '';
						$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
						$email = ( $rowData[ 8 ] != "" ) ? $rowData[ 8 ] : '';

						$reference_check = $wpdb->get_row("SELECT id,reference FROM $thTable WHERE `reference` LIKE '".$reference."%'");
						$validationError = [];
						if( !empty( $reference ) && $reference_check ){
							$rowError = true;
							$validationError[] = __('Reference is duplicate',CIP_TXTDOMAIN);
						}
						if( $rowError === true ){
							$log_msg = getOrdinal( $rowCounter ) . ' row :: ' . $reference . ' :: failed ' . implode(', ', $validationError).'<br/>';
							$countError++;
							$error = 1;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

					}
					$importNoticeMsg = sprintf( __('%s row reference checked', CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$msg2 = sprintf( __('%s row reference checked',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$lastMsg = "";
					$totalMsg = "";
					if( isset( $_POST['isLast'] ) && $_POST['isLast'] == true ){
						$lastMsg = __('User status checking started...', CIP_TXTDOMAIN);
						$totalMsg = sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_line );
					}
					$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $total_line, 'msg2' => $msg2 , 'lastMsg' => $lastMsg , 'totalMsg' => $totalMsg );
				}
			}

		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['userstatus_check'] ) && $_POST['userstatus_check'] == 'yes' ) ){ // userstatus_check process
			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];
			$fileName = $_FILES['th_csv_file']['name'];
			$pathFileName = pathinfo($fileName, PATHINFO_FILENAME);
			$pathFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$underscroePos = strrpos( $pathFileName, "_" );
			$yearWeekextract = substr( $pathFileName, $underscroePos+1 );
			$fileNameWithoutNumber = substr( $fileName, 0, $underscroePos );
			if( str_contains($pool_reference, 'BNS') ){
				$weekPos = strripos( $_POST['pool_reference'], "-" );
				$weekNumber = mb_substr( $_POST['pool_reference'], $weekPos+1, 2 );

				$yearPos = stripos( $_POST['pool_reference'], "-" );
				$yearNumber = mb_substr( $_POST['pool_reference'], $yearPos+1, 4 );
			}else{
				$weekPos = stripos( $_POST['pool_reference'], "-" );
				$weekNumber = mb_substr( $_POST['pool_reference'], $weekPos+1, 2 );

				$yearPos = strripos( $_POST['pool_reference'], "-" );
				$yearNumber = mb_substr( $_POST['pool_reference'], $yearPos+1, 4 );
			}
			$file_content = file( $csvFile , FILE_SKIP_EMPTY_LINES);
			$total_line = count($file_content) - 1;
			/* if( $fileNameWithoutNumber == 'CSR_redemptions_week' && ctype_digit( $yearWeekextract ) ){
				$week_number = mb_substr($yearWeekextract, 4);
				$year_number = mb_substr($yearWeekextract, 0, 4);
			} */
			$csr_segmentation = 100;
			if( isset( $_POST['csr_segmentation'] ) && $_POST['csr_segmentation'] >= 10 ){
				$csr_segmentation = $_POST['csr_segmentation'];
			}
			// if( ($handle = fopen($csvFile, 'r')) !== false ){
			if( isset( $_SESSION['csvArray'] ) && !empty( $_SESSION['csvArray'] ) ){

				$csvArray = $_SESSION['csvArray'];
				$splitting_id = $_POST['verification_id'];
				$splittedParts = $csvArray[ $splitting_id ];
				if( !empty( $splittedParts ) && is_array( $splittedParts ) ){
					foreach( $splittedParts as $key => $rowData ){
						$rowCounter = ( $splitting_id * 100 ) + ( $key + 1 );
						$username = ( $rowData[ 1 ] != "" ) ? $rowData[ 1 ] : '';
						$reference = ( $rowData[ 2 ] != "" ) ? $rowData[ 2 ] : '';
						$eth_address = ( $rowData[ 3 ] != "" ) ? $rowData[ 3 ] : '';
						$csr_amount_initial = ( $rowData[ 4 ] != "" ) ? str_replace( ',', '', $rowData[ 4 ]) : 0;
						$first_name = ( $rowData[ 5 ] != "" ) ? $rowData[ 5 ] : '';
						$last_name = ( $rowData[ 6 ] != "" ) ? $rowData[ 6 ] : '';
						$created = ( $rowData[ 7 ] != "" ) ? $rowData[ 7 ] : '';
						$email = ( $rowData[ 8 ] != "" ) ? $rowData[ 8 ] : '';
						$source = ( $rowData[ 9 ] != "" ) ? $rowData[ 9 ] : '';
						$member_status = "active";
						/*$client = new \GuzzleHttp\Client();
						$request_url = 'https://amplivo.com/api/userstatus/get?username=' . $username;
						$responseStatusCode = "";
						try {
							$response = $client->request('GET', $request_url);
						}catch (GuzzleHttp\Exception\ClientException $e) {
							$response = $e->getResponse();
						}
						$responseStatusCode = $response->getStatusCode();
						$amplivoStatus = json_decode( $response->getBody(), true );
						if( isset( $amplivoStatus['Status'] ) && $response->getStatusCode() == 200 ){
							$member_status = $amplivoStatus['Status'];
						}*/

						// $reference_check = $wpdb->get_results("SELECT id,reference FROM $thTable WHERE `reference` = '".$reference."'");
						// $reference_check = $wpdb->get_results("SELECT id,reference FROM $thTable WHERE `reference` LIKE '".$reference."%'");
						$validationError = [];
						/* if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
							$rowError = true;
							$validationError[] = __('Email is invalid ',CIP_TXTDOMAIN);
						}
						if( !empty( $reference ) && $reference_check ){
							$rowError = true;
							$validationError[] = __('Reference is duplicate',CIP_TXTDOMAIN);
						}
						if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
							$rowError = true;
							$validationError[] = __('csr_initial is not numeric',CIP_TXTDOMAIN);
						}
						if( !empty( $created ) && DateTime::createFromFormat('d/m/Y', $created) === false ){
							$rowError = true;
							$validationError[] = __('Created date format invalid',CIP_TXTDOMAIN);
						} */
						/*if( $responseStatusCode != 200 ){
							$rowError = true;
							$validationError[] = __('Error : Not able to get member status from amplivo',CIP_TXTDOMAIN);
						}*/
						/* if( $member_status != 'active' && $member_status != 'abandoned' ){
							$rowError = true;
							$validationError[] = sprintf( __('Error : found invalid member status `%s`',CIP_TXTDOMAIN), $member_status );
						}
						if( $rowError === true ){
							$log_msg = getOrdinal( $rowCounter ) . ' row :: ' . $reference . ' :: failed ' . implode(', ', $validationError).'<br/>';
							$countError++;
							$error = 1;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$created_formatted = "";
						if( $created ){
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $created);
							if( $formattedCDate ){
								$created_formatted = $formattedCDate->format('d/m/Y');
							}
						} */

						$distribution_status = "";
						if( $eth_address != "") {
							$security_hold_check = $wpdb->get_row("SELECT id,corp_approved FROM $thTable WHERE `eth_address` = '".$eth_address."' AND `username` = '".$username."' AND ( `corp_approved` = 'Security Hold' OR `corp_approved` = 'Hold' )");
							if( $security_hold_check ){
								$distribution_status = $security_hold_check->corp_approved;
							}
						}else if( empty( $eth_address ) ){
							// $distribution_status = 'Missing CSR address';
							$distribution_status = 'Pending';
						}
						$data = [
							'username'					=>	wp_strip_all_tags( $username ),
							'reference'					=>	wp_strip_all_tags( $reference ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'first_name'				=>	wp_strip_all_tags( $first_name ),
							'last_name'					=>	wp_strip_all_tags( $last_name ),
							'created'					=>	$created,
							'email'						=>	wp_strip_all_tags( $email ),
							'csr_amount_issued'			=>	$csr_amount_issued,
							'amount_due'				=>	0,
							'distribution_status'		=>	$distribution_status,
							'member_status'				=>	$member_status,
							'pool_ref'					=>	$pool_reference,
							'source'					=>	$source,
							'week_number'				=>	$weekNumber,
							'year_number'				=>	$yearNumber,
							'csr_segmentation'			=>	$csr_segmentation,
							'import_by'					=>	get_current_user_id(),
							'import_date'				=>	date_i18n( 'Y-m-d H:i:s' ),
						];
						$inserting = $wpdb->insert( $tableTemp, $data );
						if( $inserting ){
							$countSuccess++;
						}else{
							$error = 1;
							$countError++;
							$errorText = $wpdb->last_error;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) ), 'totalCount' => $total_line, 'msg2' => $errorText );
							echo wp_json_encode( $out );
							exit;
						}
					}
					$importNoticeMsg = sprintf( __('%s row user status checked', CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$msg2 = sprintf( __('%s row user status checked',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) );
					$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $total_line, 'msg2' => $msg2 );
					if( $rowCounter == $total_line ){
						$user_type = 'sm';
						$log_type = 'weekly_redemptions_file_import';
						$logs = sprintf( __('Import weekly redemptions of week %s, file name:%s, segmentation:%s at %s', CIP_TXTDOMAIN), $yearNumber.'/'.$weekNumber, $fileName, $csr_segmentation, date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
					}
				}
			}

		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['splitting_start'] ) && $_POST['splitting_start'] == 'yes' ) ){ //splitting_start
			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTemp WHERE 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );
			$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Splitting 10% distributions started...',CIP_TXTDOMAIN), 'msg2' => __('Splitting 10% distributions started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset($_FILES['th_csv_file']['name']) && !empty($_FILES['th_csv_file']['name']) && ( isset( $_POST['splitting_data'] ) && $_POST['splitting_data'] == 'yes' ) ){ // field mapping

			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			//==================================================//
			$csvFile = $_FILES['th_csv_file']['tmp_name'];
			$pool_reference = $_POST['pool_reference'];

			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;

			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCount = 0;
			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableTemp WHERE 1 LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
					$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
					$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
					$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? str_replace( ',', '', $getTempData->csr_amount_initial) : 0;
					$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
					$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
					$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
					$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
					$source = ( $getTempData->source != "" ) ? $getTempData->source : '';
					$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
					$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
					$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
					$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
					$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';

					$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
					$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
					$validationError = [];
					if( !empty( $email ) && !filter_var($email, FILTER_VALIDATE_EMAIL) ){
						$rowError = true;
						$validationError[] = __('Email is invalid ',CIP_TXTDOMAIN);
					}
					if( !empty( $csr_amount_initial ) && !is_numeric( $csr_amount_initial ) ){
						$rowError = true;
						$validationError[] = __('csr_initial is not numeric',CIP_TXTDOMAIN);
					}
					if( !empty( $created ) && DateTime::createFromFormat('d/m/Y', $created) === false ){
						$rowError = true;
						$validationError[] = __('Created date format invalid',CIP_TXTDOMAIN);
					}
					if( $rowError === true ){
						$log_msg = getOrdinal( $getTempData->id ) . ' row :: ' . $reference . ' :: failed ' . implode(', ', $validationError).'<br/>';
						$countError++;
						$error = 1;
						$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
						$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
						$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$created_formatted = "";
					if( $created ){
						$formattedCDate = DateTime::createFromFormat('d/m/Y', $created);
						if( $formattedCDate ){
							$created_formatted = $formattedCDate->format('d/m/Y');
						}
					}
					if( $csr_amount_initial <= $csr_segmentation ){
						$admNo = $reference.'-000';
						$newAdmNo = ++$admNo;
						$amount_due = $csr_amount_initial;
						if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
							$corp_approved_10 = $distribution_status;
						}else{
							$corp_approved_10 = 'Pending';
						}
						$notes_external_10 = '| Pending 10% distribution. |';
						if( $distribution_status == 'Security Hold' ){
							$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
						}
						$notes_external_10 = notes_trim_pipe( $notes_external_10 );
						$data = [
							'username'					=>	wp_strip_all_tags( $username ),
							'reference'					=>	wp_strip_all_tags( $newAdmNo ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'first_name'				=>	wp_strip_all_tags( $first_name ),
							'last_name'					=>	wp_strip_all_tags( $last_name ),
							'created'					=>	$created_formatted,
							'email'						=>	wp_strip_all_tags( $email ),
							'csr_amount_issued'			=>	0,
							'amount_due'				=>	$amount_due,
							'distribution_status'		=>	$distribution_status,
							'member_status'				=>	$member_status,
							'corp_approved'				=>	$corp_approved_10,
							'notes_external'			=>	$notes_external_10,
							'pool_ref'					=>	$pool_reference,
							'source'					=>	$source,
							'week_number'				=>	$year_number.'/'.$week_number,
							'csr_segmentation'			=>	$csr_segmentation,
							'import_by'					=>	$import_by,
							'import_date'				=>	$import_date,
						];
						$inserting = $wpdb->insert( $thdTable, $data );
						if( $inserting ){
							$countSuccess++;
							/* $user_type = 'sm';
							$log_type = 'weekly_redemptions_split';
							$logs = sprintf( __('Split record %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
							create_weekly_distribution_cip_logs( $user_type, $log_type, $logs ); */
						}else{
							$error = 1;
							$countError++;
							$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else{
						$csr_amount_pending = $csr_amount_initial;
						$totalNumberWeek = 52;

						for( $i=0; $i < 10; $i++ ){

							$amount_due = $csr_amount_pending / ( 10 - $i );
							$amount_due = ceil( $amount_due );
							//$csr_amount_pending = $csr_amount_pending - $amount_due;

							if( $i == 0 ){
								$admNo = $reference.'-000';
							}else{
								$admNo = $newAdmNo;
							}
							$newAdmNo = ++$admNo;

							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| Pending 10% distribution. |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );
							if( $week_number > $totalNumberWeek ){
								$week_number = $week_number - $totalNumberWeek;
								$year_number = $year_number + 1;
							}else{
								$year_number = $year_number;
							}
							$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);

							$data = [
								'username'					=>	wp_strip_all_tags( $username ),
								'reference'					=>	wp_strip_all_tags( $newAdmNo ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'		=>	$csr_amount_initial,
								// 'csr_amount_initial'		=>	$csr_amount_pending,
								'first_name'				=>	wp_strip_all_tags( $first_name ),
								'last_name'					=>	wp_strip_all_tags( $last_name ),
								'created'					=>	$created_formatted,
								'email'						=>	wp_strip_all_tags( $email ),
								'csr_amount_issued'			=>	0,
								'amount_due'				=>	$amount_due,
								'distribution_status'		=>	$distribution_status,
								'member_status'				=>	$member_status,
								'corp_approved'				=>	$corp_approved_10,
								'notes_external'			=>	$notes_external_10,
								'pool_ref'					=>	$pool_reference,
								'source'					=>	$source,
								'week_number'				=>	$new_week_number,
								'csr_segmentation'			=>	$csr_segmentation,
								'import_by'					=>	$import_by,
								'import_date'				=>	$import_date,
							];

							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$inserting = $wpdb->insert( $thdTable, $data );
							if( $inserting ){
								$countSuccess++;
								/* $user_type = 'sm';
								$log_type = 'weekly_redemptions_split';
								$logs = sprintf( __('Split record %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
								create_weekly_distribution_cip_logs( $user_type, $log_type, $logs ); */
							}else{
								$error = 1;
								$countError++;
								$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
							// $week_number++;
							$week_number = $week_number + 4;

						}
					}
					$rowDataCount = $getTempData->id;
				}
				$getProceedCount = $wpdb->get_var("SELECT COUNT(id) FROM $thdTable WHERE 1");
				$importNoticeMsg = sprintf( __('%s row proceed, %s records inserted<br/>', CIP_TXTDOMAIN), $rowDataCount, $getProceedCount );
				// $msg2 = sprintf( __('%s row splitting process complete',CIP_TXTDOMAIN), getOrdinal( $splitting_id ) );
				$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $rowDataCount );
			}

		}
	}
	echo wp_json_encode( $out );
	exit;
}
// 5078 code
add_action('wp_ajax_cip_sm_weekly_distribution_export_act','cip_sm_weekly_distribution_export_act');
function cip_sm_weekly_distribution_export_act(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN), 'msg2' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableWeeklyDistributionExport = $wpdb->prefix.'weekly_distribution_export';
	if( isset( $_POST['fetch_week_data'] ) && $_POST['fetch_week_data'] == 'yes' && !empty( $_POST['week_number'] ) ){
		$weekNumberPost = $_POST['week_number'];
		$weekPos = stripos( $weekNumberPost, "/" );
		$monthNumberNoneZero = (int)mb_substr( $weekNumberPost, $weekPos+1 );
		$yearNumber = mb_substr( $weekNumberPost, 0, 4 );
		$weekNumberNotZero = $yearNumber.'/'.$monthNumberNoneZero;
		$updateRemaining = $wpdb->query( $wpdb->prepare( "UPDATE $tableTokenHolder SET `text_8` = %s WHERE ( `text_10` = '%s' OR `text_10` = '%s' )", 'remaining', $_POST['week_number'], $weekNumberNotZero ) );
		// $getWeeklyHolderData = $wpdb->get_results( "SELECT * FROM $tableTokenHolder WHERE ( `_user_status` = 'active' OR `_user_status` = 'abandoned' ) AND `corp_approved` = 'Pending' AND `text_10` = '".$_POST['week_number']."' AND `pool_ref` NOT LIKE 'expired%' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) " );
		$getWeeklyHolderData = $wpdb->get_results( "SELECT * FROM $tableTokenHolder WHERE ( `_user_status` = 'active' OR `_user_status` = 'abandoned' ) AND `corp_approved` = 'Pending' AND `text_8` = 'remaining' AND `pool_ref` NOT LIKE 'expired%' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) " );

		$delete = $wpdb->query("TRUNCATE TABLE `".$tableWeeklyDistributionExport."`");

		if( $getWeeklyHolderData ){
			foreach( $getWeeklyHolderData as $weekData ){
				$data = array(
					'username'				=>	$weekData->username,
					'reference'				=>	$weekData->reference,
					'eth_address'			=>	$weekData->eth_address,
					'csr_amount_initial'	=>	$weekData->csr_amount_initial,
					'first_name'			=>	$weekData->first_name,
					'last_name'				=>	$weekData->last_name,
					'created'				=>	$weekData->claim_date,
					'email'					=>	$weekData->email,
					'csr_amount_issued'		=>	$weekData->csr_amount_issued,
					'amount_due'			=>	$weekData->amount_due,
					'distribution_status'	=>	'',
					'member_status'			=>	$weekData->_user_status,
					'corp_approved'			=>	$weekData->corp_approved,
					'notes_external'		=>	$weekData->notes_external,
					'pool_ref'				=>	$weekData->pool_ref,
					'week_number'			=>	$weekData->text_10,
					'append_status'			=>	0,
					'import_by'				=>	get_current_user_id(),
					'import_date'			=>	date_i18n( 'Y-m-d H:i:s' )
				);
				$insert = $wpdb->insert( $tableWeeklyDistributionExport, $data );
			}
			$out = array( "error" => 0,'msg' => __('Weekly data fetched',CIP_TXTDOMAIN) );
		}else{
			$out = array( "error" => 1,'msg' => __('No records found',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('admin_post_export_weekly_distribution_act','cip_export_weekly_distribution_act_callback');
function cip_export_weekly_distribution_act_callback(){
	global $wpdb;
	$sheetCounter = 0;
	$tableName = $wpdb->prefix . 'weekly_distribution_export';
	$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableName SET `append_status` = %d", 1 ) );
	if( $statusUpdate ){
	}
	$getDistributionData = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");


	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'username', 'reference', 'eth_address', 'amount_due', 'week_number' );

	fputcsv($exportFile, $columnHeader);
	$weekNumber = "";
	foreach( $getDistributionData as $getData ){
		$weekNumber = $getData->week_number;
		$rowData = array( $getData->username, $getData->reference, $getData->eth_address, $getData->amount_due, $getData->week_number );
		fputcsv($exportFile, $rowData);
		$excelRow++;
	}
	if( !empty( $weekNumber ) ){
		$weekPos = stripos( $weekNumber, "/" );
		$week_number = mb_substr( $weekNumber, $weekPos+1 );
	}else{
		$date = new DateTime(date('Y-m-d'));
		$week_number = $date->format("W");
	}
	$current_user = wp_get_current_user();
	$logs = sprintf( __('CSR Weekly Distribution - week '. $week_number .' download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	fseek($exportFile, 0);
	$file_name = 'CSR Weekly Distribution - week '.$week_number;
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	$user_type = 'sm';
	$log_type = 'download_weekly_distribution';
	$logs = sprintf( __('Download %s at %s', CIP_TXTDOMAIN), $file_name,date_i18n('d/m/Y H:i:s') );
	create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
	exit;
}
add_action( 'wp_ajax_getWeeklyDistributionDataAction', 'getWeeklyDistributionDataActionCallback' );
function getWeeklyDistributionDataActionCallback(){
	global $wpdb;
	$out = array( "error" => 1,'msg' => __('Summary loading failed',CIP_TXTDOMAIN) );
	$tableName = $wpdb->prefix.'weekly_distribution_export';

	$html = "";
	$getDistributions = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `append_status` = 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
	$getDistributionsSummary = $wpdb->get_row("SELECT * FROM $tableName WHERE `append_status` = 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) ORDER BY `id` DESC");
	$totalRedemptions = 0;
	$totalCsr = 0;

	if( $getDistributions > 0 && $getDistributionsSummary->import_by && $getDistributionsSummary->import_date ){
		ob_start();
		$userData = get_user_by( 'id', $getDistributionsSummary->import_by );
		if( $userData ){
			echo '<p>'. sprintf( __('Data imported by : %s', CIP_TXTDOMAIN), $userData->user_login ) .'</p>';
		}
		$import_date = '—';
		try {
			$import_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', $getDistributionsSummary->import_date);
			$import_date = $import_date_obj->format('d/m/Y H:i');
		} catch (\Throwable $th) {
			$import_date = '—';
		}
		echo '<p>'. sprintf( __('Import date : %s', CIP_TXTDOMAIN), $import_date ) .'</p>';
		echo '<p>'. sprintf( __('Total %s records to update', CIP_TXTDOMAIN), number_format($getDistributions) ) .'</p>';
		/*echo '<p>'. sprintf( __('Total CSR : %s', CIP_TXTDOMAIN), number_format($totalCsr) ) .'</p>'; */
		$html = ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Summary loaded',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_update_new_csr_holders_data_act', 'cip_update_new_csr_holders_data_act_callback' );
function cip_update_new_csr_holders_data_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYUpdateNew_csr_HoldersDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableWeeklyExport = $wpdb->prefix.'weekly_distribution_export';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		if( isset( $_POST['dividing_records'] ) && $_POST['dividing_records'] == 'yes' ){
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWeeklyExport WHERE 1 AND amount_due > 0 AND corp_approved = 'Pending' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );
			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged, 'msg' => __('Updating started',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset( $_POST['updating_data'] ) && $_POST['updating_data'] == 'yes' && isset( $_POST['page_id'] ) && !empty( $_POST['page_id'] ) ){


			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;
			$rowProceed = $paged;
			$successCount = 0;
			$failedCount = 0;
			$log_msg = "";
			$week_number = "";
			$total_count = $wpdb->get_var("SELECT COUNT(`id`) FROM $tableWeeklyExport WHERE 1 AND `amount_due` > 0 AND `corp_approved` = 'Pending' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
			$getWeeklyData = $wpdb->get_results("SELECT * FROM $tableWeeklyExport WHERE 1 AND `amount_due` > 0 AND `corp_approved` = 'Pending' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) LIMIT ".$per_page." OFFSET ".$paged."");

			if( $getWeeklyData ){
				foreach( $getWeeklyData as $getWeek ){
					$notes_external = "| Partially issued (10%) |";
					if( $getWeek->csr_amount_initial <= $getWeek->csr_segmentation ){ //full issued
						$notes_external = "";
					}
					$week_number = $getWeek->week_number;
					$data = array(
						'csr_amount_issued'		=>	$getWeek->amount_due,
						'amount_due'			=>	0,
						'corp_approved'			=>	'Issued',
						'notes_external'		=>	$notes_external,
						'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
						'text_8'				=>	NULL,
						'date_1'				=>	date_i18n( 'Y-m-d H:i:s' ),
					);
					$where = array(
						'reference'	=>	$getWeek->reference
					);
					$update = $wpdb->update( $tableTokenHolder, $data, $where );
					if( $update ){
						$successCount++;
						$rowProceed++;
						$user_type = 'sm';
						$log_type = 'weekly_redemptions_update_to_issued';
						$logs = sprintf( __('Update weekly records to Issued of reference:%s %s at %s', CIP_TXTDOMAIN), $getWeek->reference, json_encode( $data ),date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );

					}else{
						$log_msg .= '<p>'.sprintf( __('Reference :: %s, update failed', CIP_TXTDOMAIN), $getWeek->reference ).'</p>';
						$failedCount++;
						break;
					}
				}
				if( $total_count == $rowProceed ){
					update_option('last_weekly_distribution', $week_number );
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableWeeklyExport."`");
					$out = array( "error" => 0, 'msg' => sprintf( __('%s row(s) updated', CIP_TXTDOMAIN),$rowProceed ), 'total_msg' => sprintf( __('%s<br/>Total : %s<br/>Updated : %s<br/>Failed : %s',CIP_TXTDOMAIN),$log_msg, $total_count, $rowProceed, $failedCount  ), 'isLastStep' => 1 );
				}else{
					$out = array( "error" => 0, 'total_items' => $total_count, 'msg' => sprintf( __('%s row(s) updated', CIP_TXTDOMAIN),$rowProceed ), 'isLastStep' => 0 );
				}
			}
			/*$getWeeklyData = $wpdb->get_results("SELECT * FROM $tableWeeklyExport WHERE 1 AND amount_due > 0 AND corp_approved = 'Pending' AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
			$runCount = 0;
			$successCount = 0;
			$failedCount = 0;
			$total_count = count( $getWeeklyData );
			$log_msg = "";
			$week_number = "";
			if( $getWeeklyData ){
				foreach( $getWeeklyData as $getWeek ){

					$runCount++;

					$notes_external = "Partially issued (10%)";
					if( $getWeek->csr_amount_initial <= $getWeek->csr_segmentation ){ //full issued
						$notes_external = "";
					}

					$week_number = $getWeek->week_number;
					$data = array(
						'csr_amount_issued'		=>	$getWeek->amount_due,
						'amount_due'			=>	0,
						'corp_approved'			=>	'Issued',
						'notes_external'		=>	$notes_external,
						'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
						'text_8'				=>	NULL,
						'date_1'				=>	date_i18n( 'Y-m-d H:i:s' ),
					);
					$where = array(
						// 'id'	=>	$getTokenHolder->id
						'reference'	=>	$getWeek->reference
					);
					$update = $wpdb->update( $tableTokenHolder, $data, $where );
					if( $update ){
						$successCount++;
						$delete = $wpdb->delete( $tableWeeklyExport, ['id' => $getWeek->id ] );
						$user_type = 'sm';
						$log_type = 'weekly_redemptions_update_to_issued';
						$logs = sprintf( __('Update weekly records to Issued of reference:%s %s at %s', CIP_TXTDOMAIN), $getWeek->reference, json_encode( $data ),date_i18n('d/m/Y H:i:s') );
						create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );

					}else{
						$log_msg .= '<p>'.sprintf( __('Reference :: %s, update failed', CIP_TXTDOMAIN), $getWeek->reference ).'</p>';
						$failedCount++;
						break;
					}
				}
				if( $total_count == $successCount ){
					update_option('last_weekly_distribution', $week_number );
				}
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableWeeklyExport."`");
				$out = array( "error" => 0,'msg' => sprintf( __('%s<br/>Total : %s<br/>Updated : %s<br/>Failed : %s',CIP_TXTDOMAIN),$log_msg, $total_count, $successCount, $failedCount  ) );
			}*/
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancel_update_process', 'cip_cancel_update_process_callback' );
function cip_cancel_update_process_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYCancelupdateDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'weekly_distribution_export';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('Cancelled',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function create_weekly_distribution_cip_logs( $user_type = 'sa', $log_type = '', $logs = '' ){
	global $wpdb;
	$tableLog = $wpdb->prefix.'cip_logs';
	$user = wp_get_current_user();
	$userData = get_user_by( 'id', $user->ID );
	$userEmail = $userData->user_email;
	$logs = $logs . ' by '.$userEmail;
	$logData = array(
		'user_id'	=>	$user->ID,
		'user_type'	=>	$user_type,
		'log_type'	=>	$log_type,
		'logs'		=>	$logs,
		'_date'		=>	date_i18n('Y-m-d H:i:s'),
	);
	$log_insert = $wpdb->insert( $tableLog, $logData );
}
//5216 code
add_action( 'wp_ajax_smcreate_memberassitant_action', 'smcreate_memberassitant_action_callback' );
function smcreate_memberassitant_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPSMCreateMAUserCIP_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$email = $_POST['email'];
		if( !filter_var($email, FILTER_VALIDATE_EMAIL) ){
			$out = array( "error" => 1,'msg' => __('Email is invalid',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$first_name = $_POST['first_name'];
		$last_name = $_POST['last_name'];
		$userdata = array(
			'user_login'    =>   $email,
			'user_email'    =>   $email,
			'first_name'    =>   $first_name,
			'last_name'     =>   $last_name,
			'role'          =>   'member_assistant'
		);
		$user = wp_insert_user( $userdata );
		if( !is_wp_error( $user ) ){
			$maUser = new WP_User( $user );
			if( $maUser ){
				$maUser->add_role('member');
			}
			$subject = __('You account has been created Succefully!', CIP_TXTDOMAIN);
			$message = __('You are registered Succesfully on our website', CIP_TXTDOMAIN);
			wp_mail($email,$subject,$message);
			$out = array( "error" => 0,'msg' => __('New member assistant user is registered successfully.',CIP_TXTDOMAIN) );
		}else{
			$out = array( "error" => 1,'msg' => $user->get_error_message() );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//4966
add_action( 'wp_ajax_get_form_member_ethaddress_action', 'cip_get_form_member_ethaddress_action_callback' );
function cip_get_form_member_ethaddress_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'member' ) ){
		global $wpdb;
		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$decryptedId_raw = base64_decode( $_POST['Memberth'] );
		$tokenHolderId = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw ) );
		$getData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE 1 AND id = ".$tokenHolderId."");

		if( $getData ){
			$encrypt_thid = base64_encode( $tokenHolderId . $refAccount );
			ob_start();
			$total_step = 4;
			?>
			<div class="container-fluid">
				<div class="row justify-content-center">
					<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mt-2 mb-2">
						<div class="card">
							<form name="send_pending_ethaddressmember" class="send_pending_ethaddressmember" id="msform">
							<!-- progressbar -->
								<ul id="progressbar">
									<li class="active" id="fieldmapping"><strong><?php _e('Step 1',CIP_TXTDOMAIN) ?></strong></li>
									<li id="fieldmapping"><strong><?php _e('Step 2',CIP_TXTDOMAIN) ?></strong></li>
									<li id="fieldmapping"><strong><?php _e('Step 3',CIP_TXTDOMAIN) ?></strong></li>
									<li id="fieldmapping"><strong><?php _e('Step 4',CIP_TXTDOMAIN) ?></strong></li>
								</ul>
								<div class="progress">
									<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
								</div>
								<br> <!-- fieldsets -->
								<fieldset class="step_0">
									<div class="form-card">
										<div class="row">
											<div class="col-12">
												<p class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></p>
											</div>
										</div>
										<div class="form-group">
											<label for="csrwalletaddress" class="col-form-label">Enter your CSR wallet address</label>
											<input type="text" class="form-control" id="csrwalletaddress" name="csrwalletaddress" required />
											<small class="form-text text-muted"><?php _e('MetaMask will ask you to verify your wallet address. This action does not charge you any fees, nor does it make any changes to your CSR holdings.', CIP_TXTDOMAIN); ?></small>
											<p class="form_response"></p>
											<?php if( isset( $_POST['isChangeEth'] ) && $_POST['isChangeEth'] == 1 && !empty( $getData->eth_address ) ){ ?>
												<input type="hidden" name="action" value="sendAddressChangeMemberPendingAct" />
												<input type="hidden" name="isChangeEth" value="<?php echo $_POST['isChangeEth']; ?>" />
												<input type="hidden" name="_micro" value="<?php echo wp_create_nonce( $refAccount . '_isChange' ); ?>" />
											<?php }else{ ?>
												<input type="hidden" name="action" value="sendAddressMemberPendingAct" />
												<input type="hidden" name="_micro" value="<?php echo wp_create_nonce( $refAccount ); ?>" />
											<?php } ?>
											<input type="hidden" name="Memberth" value="<?php echo $encrypt_thid; ?>" />
										</div>
									</div>
									<input type="button" name="next" class="next action-button" value="Next" />
								</fieldset>

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

										<div class="row align-items-center pb-5">
											<div class="col">
												<div class="form-group">
													<label for="member_passport"><?php _e('Government issued photo ID', CIP_TXTDOMAIN); ?></label>
													<input type="file" class="form-control-file border" id="member_passport" name="member_passport" />
													<i><?php _e('e.g. passport, driving license, ID card etc.', CIP_TXTDOMAIN); ?></i><br/>
													<i><?php _e('Only jpg, jpeg, or png formats are valid. Max file size 8MB', CIP_TXTDOMAIN); ?></i>
												</div>
											</div>
											<div class="col text-center">
												<img src="<?php echo CIP_PLUGIN_FOLDER.'images/dummy-passport.png'; ?>" class="identification_image_passport" />
											</div>
										</div>
									</div>
									<input type="button" name="next" class="next action-button" value="Next" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
								</fieldset>
								<fieldset class="step_2">
									<div class="form-card">
										<div class="row">
											<div class="col-12">
												<p class="steps"><?php echo sprintf('Step %s - %s', 3, $total_step); ?></p>
											</div>
										</div>

										<div class="row align-items-center pb-5">
											<div class="col">
												<div class="form-group">
													<label for="piece_paper_wallet_address"><?php _e('Upload your selfie', CIP_TXTDOMAIN); ?></label>
													<input type="file" class="form-control-file border" id="piece_paper_wallet_address" name="piece_paper_wallet_address" />
													<i><?php _e('Only jpg, jpeg, or png formats are valid. Max file size 8MB', CIP_TXTDOMAIN); ?></i>
													<br/>
													<ul>
														<li><?php _e('Take a selfie holding a plain piece of white paper with CSRNow.com, todays date, and Your CSR address clearly written on it.', CIP_TXTDOMAIN); ?></li>
														<li><?php _e('Hold your ID card in your hand, along with the piece of paper.', CIP_TXTDOMAIN); ?></li>
														<li><?php _e('Ensure that your face is completely visible and your hand does not obscure your ID card details.', CIP_TXTDOMAIN); ?></li>
													</ul>
												</div>
											</div>
											<div class="col text-center">
												<img src="<?php echo CIP_PLUGIN_FOLDER.'images/dummy-info-passport-hold.jpg'; ?>" class="img-fluid" />
											</div>
										</div>
									</div>
									<input type="button" name="next" class="next action-button" value="Next" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
								</fieldset>

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

										<div class="form-group form-check">
											<label class="form-check-label copy_all_checkbox">
											<?php if( isset( $_POST['isChangeEth'] ) && $_POST['isChangeEth'] == 1 && !empty( $getData->eth_address ) ){ ?>
												<input class="form-check-input" type="checkbox" name="updateall_fill" value="1" style="margin-top: 0;"> <?php echo sprintf( __('Change the CSR wallet address on all rows with address <span class="eth_address_mono">%s</span> to <span class="new_address_change eth_address_mono"></span>', CIP_TXTDOMAIN), $getData->eth_address ); ?>
											<?php }else{ ?>
												<input class="form-check-input" type="checkbox" name="blank_fill" value="1" style="margin-top: 0;"> <?php _e('Use this CSR wallet address on all rows on CSRNow.com which do not have an address now.', CIP_TXTDOMAIN); ?>
											<?php } ?>
											</label>
										</div>
										<div class="form-group form-check confirm_resume_section"></div>
									</div>
									<input type="button" name="next" class="next action-button" value="Confirm" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
								</fieldset>
							</form>
						</div>
					</div>
				</div>
			</div>
			<?php
			$html = ob_get_clean();
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sendAddressMemberPendingAct','cip_sendAddressMemberPendingAct_callback');
function cip_sendAddressMemberPendingAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableAddressPending = $wpdb->prefix.'csr_address_pending';
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
		$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
		echo wp_json_encode( $out );
		exit;
	}
	if( wp_verify_nonce( $_POST['_micro'], $refAccount ) ){
		if( !empty( $_POST['csrwalletaddress'] ) && ( isset( $_POST['signature'] ) && !empty( $_POST['signature'] ) ) && $_POST['verifyingProcess'] == 'yes' ){ // sign verify
			$message = 'I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] );
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] ), $_POST['signature'], strtolower( $_POST['csrwalletaddress'] ));
			if( $verified ){

				$ip_address = cip_get_client_ip();
				$logs = sprintf( __('MetaMask\'s signature & message of %s is signature : %s, message : %s, ip : %s. At %s', CIP_TXTDOMAIN), $refAccount, $_POST['signature'], $message, $ip_address, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','member', $logs, true );
				$updateRowCount = 0;

				$decryptedId_raw = base64_decode( $_POST['Memberth'] );
				$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw ) );
				$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccount."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
				if( $getCurrentMembers ){
					foreach( $getCurrentMembers as $getCurrentMember ){
						if( $refAccount ){
							$updateRowCount++;
						}
					}
				}
				$checkDirectKyc = $wpdb->get_row("SELECT * FROM $tableName WHERE `id` = ".$_microid." AND `email` = '".$refAccount."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( `csr_amount_initial` IS NULL OR `csr_amount_initial` = '' OR `csr_amount_initial` = 0 ) AND ( `csr_amount_issued` IS NULL OR `csr_amount_issued` = '' OR `csr_amount_issued` = 0 ) AND ( `amount_due` IS NULL OR `amount_due` = '' OR `amount_due` = 0 )");
				if( $checkDirectKyc ){
					$updateData = ['eth_address' => $_POST['csrwalletaddress'], 'note_10' => null, 'sign_verify' => 1, 'last_update' => date_i18n('Y-m-d H:i A') ];
					if( $checkDirectKyc->corp_approved == 'Missing CSR address'  ){
						$new_corp_approved = "Pending";
						if( $checkDirectKyc->pool_ref == 'C' || $checkDirectKyc->pool_ref == 'F' || $checkDirectKyc->pool_ref == 'H' || $checkDirectKyc->pool_ref == 'I' || $checkDirectKyc->pool_ref == 'J' ){
							$new_corp_approved = "Under review";
						}
						$updateData = wp_parse_args( ['corp_approved' => $new_corp_approved], $updateData );
					}
					$update = $wpdb->update( $tableName, $updateData, ['id' => $checkDirectKyc->id ] );
					if( $update ){
						$user_id = get_current_user_id();
						$userData = get_user_by( 'id', $user_id );
						$logs = sprintf( __('CSR address %s direct approved of %s by SA(%s) at %s', CIP_TXTDOMAIN),$_POST['csrwalletaddress'], $checkDirectKyc->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );
						$out = array( "error" => 0, 'msg' => __('CSR Wallet added successfully', CIP_TXTDOMAIN), 'updateRowCount' => 0, 'html' => '', 'isDirectAdded' => 1 );
						echo wp_json_encode( $out );
						exit;
					}

				}
				$html = "";
				if( $updateRowCount <= 1 ){
					$html = '<div class="alert alert-secondary row_update_info only_one_update_info">NOTE: '. sprintf( _n( 'You are about to update %s row.', 'You are about to update %s rows.', $updateRowCount, CIP_TXTDOMAIN ), $updateRowCount ) .'</div>';
				}

				$out = array( "error" => 0, 'msg' => __('Verification Sucess', CIP_TXTDOMAIN), 'updateRowCount' => $updateRowCount, 'html' => $html, 'isDirectAdded' => 0 );
			}else{
				$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
			}
		}else if( !empty( $_POST['csrwalletaddress'] ) && $_POST['countUpdateRow'] == 'yes' ){ //count update row
			$updateRowCount = 0;
			$blank_fill = ( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ) ? 1 : 0;

			$decryptedId_raw = base64_decode( $_POST['Memberth'] );
			$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw ) );
			$getCsrDataExists = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email != '".$refAccount."' AND email IS NOT NULL AND email <> '') AND `sign_verify` = 1");
			if( $getCsrDataExists ){
				// $out = array( "error" => 1, 'msg' => __('Wallet address already in use', CIP_TXTDOMAIN) );
			}else{
				if( $blank_fill ){
					$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccount."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
					if( $getCurrentMembers ){
						foreach( $getCurrentMembers as $getCurrentMember ){
							if( $refAccount ){
								$updateRowCount++;
							}
						}
					}
				}else{
					$getCurrentMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_microid." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccount."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '')");
					if( $getCurrentMember ){
						$updateRowCount++;
					}
				}
			}
			$html = '<div class="alert alert-secondary row_update_info">NOTE: '. sprintf( _n( 'You are about to update %s row.', 'You are about to update %s rows.', $updateRowCount, CIP_TXTDOMAIN ), $updateRowCount ) .'</div>';
			$out = array( "error" => 0, 'html' => $html,'msg' => __('Success', CIP_TXTDOMAIN) );
		}else{ //insert for pending review
			$pendingAddressLists = $wpdb->get_var(" SELECT COUNT(id) FROM $tableAddressPending WHERE email = '".$refAccount."' AND status = 2 AND type = 'request' ORDER BY `id` DESC ");
			if( $pendingAddressLists ){
				$out = array( "error" => 1,'msg' => __('Your request already in pending for review',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] ), $_POST['returnedSignature'], strtolower( $_POST['csrwalletaddress'] ));
			if( $verified ){

				if( $_FILES['member_passport']['tmp_name'] != "" ){ //passport file

					if(!empty($_FILES["member_passport"]["name"]) && is_uploaded_file($_FILES['member_passport']['tmp_name']) ){

						$fileName = basename($_FILES["member_passport"]["name"]);

						$fileinfo = @getimagesize($_FILES["member_passport"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["member_passport"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Photo ID file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['member_passport']['tmp_name'];
						$member_passport = file_get_contents($_FILES['member_passport']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}

				if( $_FILES['piece_paper_wallet_address']['tmp_name'] != "" ){ //piece_paper_wallet_address file

					if(!empty($_FILES["piece_paper_wallet_address"]["name"]) && is_uploaded_file($_FILES['piece_paper_wallet_address']['tmp_name']) ){

						$fileName = basename($_FILES["piece_paper_wallet_address"]["name"]);

						$fileinfo = @getimagesize($_FILES["piece_paper_wallet_address"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["piece_paper_wallet_address"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Selfie file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['piece_paper_wallet_address']['tmp_name'];
						$piece_paper_wallet_address = file_get_contents($_FILES['piece_paper_wallet_address']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$blank_fill = ( isset( $_POST['blank_fill'] ) && $_POST['blank_fill'] == 1 ) ? 1 : 0;
				$uniqKey = uniqid() . '-' . date_i18n('YmdHis');
				$decryptedId_raw = base64_decode( $_POST['Memberth'] );
				$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount) ), '', urlencode( $decryptedId_raw));
				if( base64_encode( $_microid . $refAccount ) != $_POST['Memberth']){
					$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				//uniqKey update for specific records
				$updateCount = 0;
				$getCsrDataExists = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['csrwalletaddress'] ."' AND ( email != '".$refAccount."' AND email IS NOT NULL AND email <> '') AND `sign_verify` = 1");
				if( $getCsrDataExists ){
					$out = array( "error" => 1, 'msg' => __('Wallet address already in use', CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}else{
					if( $blank_fill ){
						$getCurrentMembers = $wpdb->get_results(" SELECT * FROM $tableName WHERE email = '".$refAccount."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
						if( $getCurrentMembers ){
							foreach( $getCurrentMembers as $getCurrentMember ){
								if( $refAccount ){
									$data = [ 'note_10' => $uniqKey ];
									$where = [ 'id' => $getCurrentMember->id ];
									$update = $wpdb->update( $tableName, $data, $where );
									if( $update ){
										$updateCount++;
									}
								}
							}
						}
					}else{
						$getCurrentMember = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ".$_microid." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccount."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '')");
						if( $getCurrentMember ){
							if( $refAccount ){
								$data = [ 'note_10' => $uniqKey ];
								$where = [ 'id' => $getCurrentMember->id ];
								$update = $wpdb->update( $tableName, $data, $where );
								if( $update ){
									$updateCount++;
								}
							}
						}
					}
				}
				$username = "";
				$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email`,`username` FROM $tableName WHERE 1 AND id = ".$_microid." AND ( eth_address IS NULL OR eth_address = '' ) AND email = '".$refAccount."'");
				if( $getWalletRecord ){
					$username = $getWalletRecord->username;
				}
				//uniqKey update for specific records
				$data = array(
					'email'	=>	$refAccount,
					'update_key'	=>	$uniqKey,
					'username'	=>	$username,
					'eth_address'	=>	$_POST['csrwalletaddress'],
					'member_passport'	=>	$member_passport,
					'piece_paper_wallet_address'	=>	$piece_paper_wallet_address,
					'blank_fill'	=>	$blank_fill,
					'type'	=>	'request',
					'change_type'	=>	'add',
					'status'	=>	2,
					'reject_msg'	=>	'',
					'user_date'	=>	date_i18n( 'Y-m-d H:i:s' ),
					'sa_date'	=>	null,
				);
				$insert = $wpdb->insert( $tableAddressPending, $data );
				if( $insert ){
					$logs = sprintf( __('%s requested %s row(s) to add new CSR address(%s), send to review at %s', CIP_TXTDOMAIN), $refAccount, $updateCount, $_POST['csrwalletaddress'], date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
					$out = array( "error" => 0,'msg' => __('Your request to update CSR wallet address has been received.<br>Please check back in 2 working days.',CIP_TXTDOMAIN) );
				}else{
					$out = array( "error" => 1,'msg' => __('Failed to sending CSR wallet address for verification process.<br>Please contact to support',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1, 'msg' => __('Something went wrong. Verification failed', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sendAddressChangeMemberPendingAct','cip_sendAddressChangeMemberPendingAct_callback');
function cip_sendAddressChangeMemberPendingAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableAddressPending = $wpdb->prefix.'csr_address_pending';
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
		$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
		echo wp_json_encode( $out );
		exit;
	}
	if( wp_verify_nonce( $_POST['_micro'], $refAccount . '_isChange' ) ){
		if( !empty( $_POST['csrwalletaddress'] ) && ( isset( $_POST['signature'] ) && !empty( $_POST['signature'] ) ) && $_POST['verifyingProcess'] == 'yes' ){ // sign verify
			$message = 'I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] );
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] ), $_POST['signature'], strtolower( $_POST['csrwalletaddress'] ));
			if( $verified ){


				$ip_address = cip_get_client_ip();
				$logs = sprintf( __('MetaMask\'s signature & message of %s is signature : %s, message : %s, ip : %s. At %s', CIP_TXTDOMAIN), $refAccount, $_POST['signature'], $message, $ip_address, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','member', $logs, true );
				$updateRowCount = 0;

				$decryptedId_raw = base64_decode( $_POST['Memberth'] );
				$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw));
				$getTokenHolderData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id` = ". $_microid ." ");
				if( $getTokenHolderData ){
					$getUpdatingData = $wpdb->get_results("SELECT * FROM $tableName WHERE `username` = '".$getTokenHolderData->username."' AND ( `eth_address` IS NOT NULL OR eth_address <> '' ) AND `eth_address` = '".$getTokenHolderData->eth_address."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
					if( $getUpdatingData ){
						foreach( $getUpdatingData as $getUpdating ){
							$updateRowCount++;
						}
					}
				}
				$html = "";
				if( $updateRowCount <= 1 ){
					$html = '<div class="alert alert-secondary row_update_info only_one_update_info">NOTE: '. sprintf( _n( 'You are about to update %s row.', 'You are about to update update %s rows.', $updateRowCount, CIP_TXTDOMAIN ), $updateRowCount ) .'</div>';
				}

				$out = array( "error" => 0, 'msg' => __('Verification Sucess', CIP_TXTDOMAIN), 'updateRowCount' => $updateRowCount, 'html' => $html, 'new_address' => $_POST['csrwalletaddress'], 'isDirectAdded' => 0 );
			}else{
				$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
			}
		}else if( !empty( $_POST['csrwalletaddress'] ) && $_POST['countUpdateRow'] == 'yes' ){ //count update row

			$updateRowCount = 0;
			$updateall_fill = ( isset( $_POST['updateall_fill'] ) && $_POST['updateall_fill'] == 1 ) ? 1 : 0;

			$decryptedId_raw = base64_decode( $_POST['Memberth'] );
			$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw));
			$getTokenHolderData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id` = ". $_microid ." ");
			if( $getTokenHolderData ){
				if( $updateall_fill ){
					$getUpdatingData = $wpdb->get_results("SELECT * FROM $tableName WHERE `username` = '".$getTokenHolderData->username."' AND ( `eth_address` IS NOT NULL OR eth_address <> '' ) AND `eth_address` = '".$getTokenHolderData->eth_address."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
					if( $getUpdatingData ){
						foreach( $getUpdatingData as $getUpdating ){
							$updateRowCount++;
						}
					}
				}
			}

			$html = '<div class="alert alert-secondary row_update_info">NOTE: '. sprintf( _n( 'You are about to update %s row.', 'You are about to update %s rows.', $updateRowCount, CIP_TXTDOMAIN ), $updateRowCount ) .'</div>';
			// $out = array( "error" => 0, 'html' => $html,'msg' => __('Success', CIP_TXTDOMAIN) );
			$out = array( "error" => 0, 'html' => $html,'msg' => $temp );

		}else if( $_POST['passportSizeCheck'] == 'yes' ){ //Size validation check
			if( $_FILES['member_passport']['tmp_name'] != "" ){ //passport file

				if(!empty($_FILES["member_passport"]["name"]) && is_uploaded_file($_FILES['member_passport']['tmp_name']) ){

					$fileName = basename($_FILES["member_passport"]["name"]);

					$fileinfo = @getimagesize($_FILES["member_passport"]["tmp_name"]);

					$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
					$width = $fileinfo[0];
					$height = $fileinfo[1];

					$allowTypes = array('jpg','png','jpeg');

					if(!in_array($fileType, $allowTypes)){
						$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}else if (($_FILES["member_passport"]["size"] > 8000000)){
						$out = array( "error" => 1,'msg' => __('Photo ID file size exceeds 8MB',CIP_TXTDOMAIN), 'size' => $_FILES["member_passport"]["size"] );
						echo wp_json_encode( $out );
						exit;
					}
					$out = array( "error" => 0,'msg' => __('File size allowed',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else if( $_POST['selfieSizeCheck'] == 'yes' ){ //Size validation check
			if( $_FILES['piece_paper_wallet_address']['tmp_name'] != "" ){ //piece_paper_wallet_address file

				if(!empty($_FILES["piece_paper_wallet_address"]["name"]) && is_uploaded_file($_FILES['piece_paper_wallet_address']['tmp_name']) ){

					$fileName = basename($_FILES["piece_paper_wallet_address"]["name"]);

					$fileinfo = @getimagesize($_FILES["piece_paper_wallet_address"]["tmp_name"]);

					$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
					$width = $fileinfo[0];
					$height = $fileinfo[1];

					$allowTypes = array('jpg','png','jpeg');

					if(!in_array($fileType, $allowTypes)){
						$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}else if (($_FILES["piece_paper_wallet_address"]["size"] > 8000000)){
						$out = array( "error" => 1,'msg' => __('Selfie file size exceeds 8MB',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$out = array( "error" => 0,'msg' => __('File size allowed',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{ //insert for pending review

			$pendingAddressLists = $wpdb->get_var(" SELECT COUNT(id) FROM $tableAddressPending WHERE email = '".$refAccount."' AND status = 2 AND type = 'request' ORDER BY `id` DESC ");
			if( $pendingAddressLists ){
				$out = array( "error" => 1,'msg' => __('Your request already in pending for review',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] ), $_POST['returnedSignature'], strtolower( $_POST['csrwalletaddress'] ));
			if( $verified ){

				if( $_FILES['member_passport']['tmp_name'] != "" ){ //passport file

					if(!empty($_FILES["member_passport"]["name"]) && is_uploaded_file($_FILES['member_passport']['tmp_name']) ){

						$fileName = basename($_FILES["member_passport"]["name"]);

						$fileinfo = @getimagesize($_FILES["member_passport"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["member_passport"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Photo ID file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['member_passport']['tmp_name'];
						$member_passport = file_get_contents($_FILES['member_passport']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}

				if( $_FILES['piece_paper_wallet_address']['tmp_name'] != "" ){ //piece_paper_wallet_address file

					if(!empty($_FILES["piece_paper_wallet_address"]["name"]) && is_uploaded_file($_FILES['piece_paper_wallet_address']['tmp_name']) ){

						$fileName = basename($_FILES["piece_paper_wallet_address"]["name"]);

						$fileinfo = @getimagesize($_FILES["piece_paper_wallet_address"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["piece_paper_wallet_address"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Selfie file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['piece_paper_wallet_address']['tmp_name'];
						$piece_paper_wallet_address = file_get_contents($_FILES['piece_paper_wallet_address']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$uniqKey = uniqid() . '-' . date_i18n('YmdHis');
				$updateall_fill = ( isset( $_POST['updateall_fill'] ) && $_POST['updateall_fill'] == 1 ) ? 1 : 0;

				$decryptedId_raw = base64_decode( $_POST['Memberth'] );
				$_microid = preg_replace(sprintf('/%s/', urlencode( $refAccount ) ), '', urlencode( $decryptedId_raw ));
				if( base64_encode( $_microid . $refAccount ) != $_POST['Memberth']){
					$out = array( "error" => 1,'msg' => __('There is wrong data, please contact to support',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$getTokenHolderData = $wpdb->get_row("SELECT * FROM $tableName WHERE `id` = ". $_microid ." AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
				$updateCount = 0;
				if( $getTokenHolderData ){
					if( $updateall_fill ){
						$getUpdatingData = $wpdb->get_results("SELECT * FROM $tableName WHERE `username` = '".$getTokenHolderData->username."' AND ( `eth_address` IS NOT NULL OR eth_address <> '' ) AND `eth_address` = '".$getTokenHolderData->eth_address."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '') ");
						if( $getUpdatingData ){
							foreach( $getUpdatingData as $getUpdating ){
								if( !empty( $getUpdating->eth_address ) && $getTokenHolderData->eth_address == $getUpdating->eth_address ){
									if( $refAccount ){
										$data = [ 'note_10' => $uniqKey ];
										$where = [ 'id' => $getUpdating->id ];
										$update = $wpdb->update( $tableName, $data, $where );
										if( $update ){
											$updateCount++;
										}
									}
								}
							}
						}
					}else{
						if( !empty( $getTokenHolderData->eth_address ) ){
							if( $refAccount ){
								$data = [ 'note_10' => $uniqKey ];
								$where = [ 'id' => $getTokenHolderData->id ];
								$update = $wpdb->update( $tableName, $data, $where );
								if( $update ){
									$updateCount++;
								}
							}
						}
					}
					$username = "";
					$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email`,`username` FROM $tableName WHERE 1 AND `id` = ". $_microid ." AND ( `eth_address` IS NOT NULL OR eth_address <> '' ) AND email = '".$refAccount."' AND `eth_address` = '".$getTokenHolderData->eth_address."' ");
					if( $getWalletRecord ){
						$username = $getWalletRecord->username;
					}
					//uniqKey update for specific records
					$data = array(
						'email'	=>	$refAccount,
						'update_key'	=>	$uniqKey,
						'username'	=>	$username,
						'eth_address'	=>	$_POST['csrwalletaddress'],
						'member_passport'	=>	$member_passport,
						'piece_paper_wallet_address'	=>	$piece_paper_wallet_address,
						'blank_fill'	=>	$updateall_fill,
						'type'	=>	'request',
						'change_type'	=>	'edit',
						'status'	=>	2,
						'reject_msg'	=>	'',
						'user_date'	=>	date_i18n( 'Y-m-d H:i:s' ),
						'sa_date'	=>	null,
					);
					$insert = $wpdb->insert( $tableAddressPending, $data );
					if( $insert ){
						$logs = sprintf( __('%s requested %s row(s) to change CSR address from %s to %s, send to review at %s', CIP_TXTDOMAIN), $refAccount, $updateCount, $getTokenHolderData->eth_address, $_POST['csrwalletaddress'], date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
						$out = array( "error" => 0,'msg' => __('Your request to update CSR wallet address has been received.<br>Please check back in 2 working days.',CIP_TXTDOMAIN) );
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to sending CSR wallet address for verification process.<br>Please contact to support',CIP_TXTDOMAIN) );
					}
				}
			}else{
				$out = array( "error" => 1, 'msg' => __('Something went wrong. Verification failed', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//4966
add_action( 'wp_ajax_cip_reject_csraddress_act', 'cip_reject_csraddress_act_callback' );
function cip_reject_csraddress_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyRejectCsrAddressyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableAddressPending = $wpdb->prefix.'csr_address_pending';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPpassportCIP') ), '', $decrypted_id_raw);
		$getPendingData = $wpdb->get_row("SELECT * FROM $tableAddressPending WHERE id = ".$id." AND status != 1");
		if( $getPendingData ){
			$data = array('type' => 'rejected', 'status'	=>	0, 'reject_msg' => stripslashes( $_POST['rejectMsg'] ),'sa_date' => date_i18n( 'Y-m-d H:i:s') );
			$where = array('id'	=>	$getPendingData->id);
			$update = $wpdb->update( $tableAddressPending, $data, $where );
			if( $update ){
				$update_key = $getPendingData->update_key; //updateKey remove after rejection
				if( !empty( $update_key ) ){
					$getTokenHolderUpdateKey = $wpdb->get_results("SELECT `id` FROM $tableTokenHolder WHERE `note_10` = '". $update_key ."'");
					if( $getTokenHolderUpdateKey ){
						foreach( $getTokenHolderUpdateKey as $UpdateKeyData ){
							$wpdb->update( $tableTokenHolder, ['note_10' => null], ['id' => $UpdateKeyData->id ] );
						}
					}
				}
				$noticeMsg = sprintf( __('Your requested CSR address update was rejected. The reason is : %s', CIP_TXTDOMAIN), stripslashes( $_POST['rejectMsg'] ) );
				$noticeData = array(
					"email"	=>	$getPendingData->email,
					"username"	=>	$getPendingData->username,
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$out = array( "error" => 0,'msg' => __('Rejected',CIP_TXTDOMAIN) );
				$user_id = get_current_user_id();
				$userData = get_user_by( 'id', $user_id );
				$logs = sprintf( __('CSR Address (%s) rejected of %s with reason(%s) by SA(%s) at %s', CIP_TXTDOMAIN),$getPendingData->eth_address, $getPendingData->email, $_POST['rejectMsg'], $userData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//4966
add_action( 'wp_ajax_cip_approved_csraddress_act', 'cip_approved_csraddress_act_callback' );
function cip_approved_csraddress_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyApprovedCsrAddressyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableAddressPending = $wpdb->prefix.'csr_address_pending';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPpassportCIP') ), '', $decrypted_id_raw);
		$getPendingData = $wpdb->get_row("SELECT * FROM $tableAddressPending WHERE id = ".$id." AND status != 1");
		if( $getPendingData ){
			$data = array('status'	=>	1, 'reject_msg' => '','sa_date' => date_i18n( 'Y-m-d H:i:s') );
			$where = array('id'	=>	$getPendingData->id);
			$update = $wpdb->update( $tableAddressPending, $data, $where );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Approved',CIP_TXTDOMAIN) );
				$user_id = get_current_user_id();
				$userData = get_user_by( 'id', $user_id );
				$update_key = $getPendingData->update_key;
				$isUpdateAddress = false;
				if( !empty( $update_key ) ){
					$updateCount = 0;
					if( $getPendingData->change_type == 'edit' ){
						$getTokenHolderUpdateKey = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE ( eth_address IS NOT NULL OR eth_address <> '' ) AND `note_10` = '". $update_key ."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '')");
						if( $getTokenHolderUpdateKey ){
							$checkNewAddressSH = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE eth_address = '".$getPendingData->eth_address."'  AND `corp_approved` = 'Security Hold'");
							foreach( $getTokenHolderUpdateKey as $UpdateKeyData ){
								$updateData = ['eth_address' => $getPendingData->eth_address, 'note_10' => null, 'sign_verify' => 1, 'last_update' => date_i18n('Y-m-d H:i A') ];
								if( $checkNewAddressSH ){
									$new_corp_approved = 'Security Hold';
								}else{

									$new_corp_approved = $UpdateKeyData->text_7;
									if($new_corp_approved == "" || $new_corp_approved == NULL)
						{$new_corp_approved = $UpdateKeyData->corp_approved;}
									$newExternalNotes = preg_replace(sprintf('/%s/', '| Distribution suspended until Security Hold lifted. |' ), '', $UpdateKeyData->notes_external);
									$newExternalNotes = notes_trim_pipe( $newExternalNotes );
									$updateData = wp_parse_args( ['notes_external' => $newExternalNotes], $updateData );
								}

								$updateData = wp_parse_args( ['corp_approved' => $new_corp_approved], $updateData );
								$update = $wpdb->update( $tableTokenHolder, $updateData, ['id' => $UpdateKeyData->id ] );
								if( $update ){
									$isUpdateAddress = true;
									$updateCount++;
								}
							}
						}
						if( $isUpdateAddress ){
							$email_address = $getPendingData->email;
							$eth_address = $getPendingData->eth_address;
							$update = $wpdb->update( $tableTokenHolder, ['sign_verify' => 1 ], ['email' => $email_address, 'eth_address' => $eth_address ] );
						}
					}else if( $getPendingData->change_type == 'add' ){
						$getTokenHolderUpdateKey = $wpdb->get_results("SELECT `id`,`corp_approved`,`pool_ref` FROM $tableTokenHolder WHERE ( eth_address IS NULL OR eth_address = '' ) AND `note_10` = '". $update_key ."' AND ( `corp_approved` != 'Issued' OR `corp_approved` IS NULL OR `corp_approved` = '')");
						if( $getTokenHolderUpdateKey ){
							foreach( $getTokenHolderUpdateKey as $UpdateKeyData ){
								$updateData = ['eth_address' => $getPendingData->eth_address, 'note_10' => null, 'sign_verify' => 1, 'last_update' => date_i18n('Y-m-d H:i A') ];
								if( $UpdateKeyData->corp_approved == 'Missing CSR address'  ){
									$new_corp_approved = "Pending";
									if( $UpdateKeyData->pool_ref == 'C' || $UpdateKeyData->pool_ref == 'F' || $UpdateKeyData->pool_ref == 'H' || $UpdateKeyData->pool_ref == 'I' || $UpdateKeyData->pool_ref == 'J' ){
										$new_corp_approved = "Under review";
									}
									$updateData = wp_parse_args( ['corp_approved' => $new_corp_approved], $updateData );
								}
								$update = $wpdb->update( $tableTokenHolder, $updateData, ['id' => $UpdateKeyData->id ] );
								if( $update ){
									$isUpdateAddress = true;
									$updateCount++;
								}
							}
						}
						if( $isUpdateAddress ){
							$email_address = $getPendingData->email;
							$eth_address = $getPendingData->eth_address;
							$update = $wpdb->update( $tableTokenHolder, ['sign_verify' => 1 ], ['email' => $email_address, 'eth_address' => $eth_address ] );
						}
					}
					if( $isUpdateAddress ){
						$logs = sprintf( __('CSR address %s approved for %s row(s) of %s by SA(%s) at %s', CIP_TXTDOMAIN),$getPendingData->eth_address, $updateCount, $getPendingData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );

						$noticeMsg = __('Your requested CSR address update is approved.', CIP_TXTDOMAIN);
						$noticeData = array(
							"email"	=>	$getPendingData->email,
							"username"	=>	$getPendingData->username,
							"notice"	=>	$noticeMsg,
							"status"	=>	1,
							"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
						);
						$wpdb->insert( $tableCipNotice, $noticeData );
					}
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_getValidateAddCsrWalletDataAct', 'cip_getValidateAddCsrWalletDataAct_callback' );
function cip_getValidateAddCsrWalletDataAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$isConfirmResumeDistribution = 0;

	if( wp_verify_nonce( $_POST['_micro'],'_XyValidateAddCsrWalletDatayX_' ) ){

		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$getSHDataExists = $wpdb->get_row("SELECT * FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND ( email = '".$refAccount."' AND email IS NOT NULL AND email <> '') AND corp_approved = 'Security Hold' ");

		if( wp_verify_nonce( $_POST['isChangeMicro'], $refAccount ) ){ //adding
			if( $getSHDataExists ){
				$out = array( "error" => 1, 'msg' => __('You cannot add this CSR address as it is presently set to Security Hold. Please choose another address or Lift the Security Hold on My Profile.', CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			$getCsrDataExists = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND ( email != '".$refAccount."' AND email IS NOT NULL AND email <> '') AND `sign_verify` = 1");
			if( $getCsrDataExists ){
				$out = array( "error" => 1, 'msg' => __('Wallet address already in use', CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $_POST['thiseth'], 'isConfirmResumeDistribution' => $isConfirmResumeDistribution );
			}
		}else if( wp_verify_nonce( $_POST['isChangeMicro'], $refAccount . '_isChange' ) ){ //changing
			if( $getSHDataExists ){
				$out = array( "error" => 1, 'msg' => __('You cannot update this CSR address as it is presently set to Security Hold. Please choose another address or Lift the Security Hold on My Profile.', CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			$decryptedId_raw = base64_decode( $_POST['Memberth'] );
			$tokenHolderId = preg_replace(sprintf('/%s/', urlencode( $refAccount) ), '', urlencode( $decryptedId_raw));
			$checkSameAddress = $wpdb->get_row("SELECT * FROM $tableName WHERE id = ". $tokenHolderId ." ");
			if( $checkSameAddress->eth_address != $_POST['thiseth'] ){
				$getCsrDataExists = $wpdb->get_results("SELECT * FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND ( email != '".$refAccount."' AND email IS NOT NULL AND email <> '') AND `sign_verify` = 1");
				if( $getCsrDataExists ){
					$out = array( "error" => 1, 'msg' => __('Wallet address already in use', CIP_TXTDOMAIN) );
				}else{
					$checkHaveSHRecords = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND ( email = '".$refAccount."' AND email IS NOT NULL AND email <> '') AND corp_approved = 'Security Hold' ");
					$currentAddressHaveSH = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $checkSameAddress->eth_address ."' AND ( email = '".$refAccount."' AND email IS NOT NULL AND email <> '') AND corp_approved = 'Security Hold' ");
					$confirmCheckboxHtml = "";
					if( !$checkHaveSHRecords && $currentAddressHaveSH ){
						$isConfirmResumeDistribution = 1;
						$confirmCheckboxHtml = '<label class="form-check-label"><input class="form-check-input" type="checkbox" name="confirmResume" class="confirmResume" value="1" style="margin-top: 0;">'. __('I understand that by updating this address all affected rows on CSRnow.com will have their status of Security Hold lifted and distribution will resume.', CIP_TXTDOMAIN). '</label>';
					}
					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $_POST['thiseth'], 'isConfirmResumeDistribution' => $isConfirmResumeDistribution, 'confirmCheckboxHtml' => $confirmCheckboxHtml );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('The CSR wallet address cannot be the same.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cipGetAddWalletAddressSignatureMsg_act','cipGetAddWalletAddressSignatureMsgCallback');
function cipGetAddWalletAddressSignatureMsgCallback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	if( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ){
		if( !empty( $_POST['thiseth'] ) ){
			$eth_address = strtolower( $_POST['thiseth'] );
			$out = array( "error" => 0, 'msg' => 'I '.$refAccount.' confirm that I own the address: '.$eth_address);
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_dismiss_notice_action','cip_dismiss_notice_action_callback');
function cip_dismiss_notice_action_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableCipNotice = $wpdb->prefix.'cip_notice';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	$decrypted_id_raw = base64_decode( $_REQUEST['thisnotice'] );
	$id = preg_replace(sprintf('/%s/', md5('CIP_Notice_CIP') ), '', $decrypted_id_raw);
	$tempDismissSession = $_SESSION['tempDismissSession'];
	$dismissData = array();
	if( !empty( $tempDismissSession ) ){
		$dismissData = json_decode( $tempDismissSession, true );
		$dismissData[] = $id;
	}else{
		$dismissData = array( $id );
	}
	if( $_POST['dont_show'] == 1 ){
		$getNotice = $wpdb->get_row("SELECT * FROM $tableCipNotice WHERE `id` = ".$id." AND `status` = 1");
		if( $getNotice ){
			$wpdb->update( $tableCipNotice, ['status' => 0], ['id' => $id] );
		}
		$out = array( "error" => 0 );
	}else{
		$_SESSION['tempDismissSession'] = json_encode( array_unique( $dismissData ) );
		$out = array( "error" => 0 );
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_cip_dismiss_notice_all_action','cip_dismiss_notice_all_action_callback');
function cip_dismiss_notice_all_action_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableCipNotice = $wpdb->prefix.'cip_notice';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	$tempDismissSession = $_SESSION['tempDismissSession'];
	$dismissData = array();
	$getNotices = $wpdb->get_results("SELECT `id` FROM $tableCipNotice WHERE `status`=1 AND `email`='".$refAccount."'");
	if( !empty( $tempDismissSession ) ){
		$dismissData = json_decode( $tempDismissSession, true );
		if( $getNotices ){
			foreach( $getNotices as $getNotice ){
				$dismissData[] = $getNotice->id;
			}
		}
	}else{
		if( $getNotices ){
			foreach( $getNotices as $getNotice ){
				$dismissData[] = $getNotice->id;
			}
		}
	}
	if( $_POST['dont_show'] == 1 ){
		$wpdb->update( $tableCipNotice, ['status' => 0], ['email' => $refAccount] );
		$out = array( "error" => 0 ,'msg' => __('Dismissed all notification', CIP_TXTDOMAIN) );
	}else{
		$_SESSION['tempDismissSession'] = json_encode( array_unique( $dismissData ) );
		$out = array( "error" => 0, 'msg' => __('Dismissed all notification', CIP_TXTDOMAIN) );
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_update_security_hold_record','update_security_hold_record_callback');
function update_security_hold_record_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'__CIPSecurityHoldRecordCIP__' ) ){
		global $wpdb;
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ){

			$decrypted_address_raw = base64_decode( $_POST['thisId'] );
			$address = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_address_raw);

			$decrypted_id_raw = base64_decode( $_POST['thisAid'] );
			$id = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_id_raw);
			if( isset( $_POST['getLiftSHFrm'] ) && $_POST['getLiftSHFrm'] == 1 ){
				$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email` FROM $tableTokenHolder WHERE `id` = ".$id." AND `email` = '".$refAccount."' AND `eth_address` = '".$address."' ");
				$allSHCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND `corp_approved` = 'Security Hold'");
				if( $allSHCount <= 0 ){
					$out = array( "error" => 1,'msg' => __('Something went wrong. You don\'t have any security hold records',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				if( $getWalletRecord ){
					ob_start();
					$total_step = 3;
					?>
					<div class="container-fluid">
						<div class="row justify-content-center">
							<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mt-2 mb-2">
								<div class="card">
									<form name="liftSHWizardFrm" class="liftSHWizardFrm" id="msform">
									<!-- progressbar -->
										<ul id="progressbar">
											<li class="active" id="fieldmapping"><strong><?php _e('Step 1',CIP_TXTDOMAIN) ?></strong></li>
											<li id="fieldmapping"><strong><?php _e('Step 2',CIP_TXTDOMAIN) ?></strong></li>
											<li id="fieldmapping"><strong><?php _e('Step 3',CIP_TXTDOMAIN) ?></strong></li>
											<!--li id="fieldmapping"><strong><?php //_e('Step 4',CIP_TXTDOMAIN) ?></strong></li-->
										</ul>
										<div class="progress">
											<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
										</div>
										<br> <!-- fieldsets -->
										<fieldset class="step_0">
											<div class="form-card">
												<div class="row">
													<div class="col-12">
														<p class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></p>
													</div>
												</div>

												<div class="row align-items-center pb-5">
													<div class="col">
														<div class="form-group">
															<label for="member_passport"><?php _e('Government issued photo ID', CIP_TXTDOMAIN); ?></label>
															<input type="file" class="form-control-file border" id="member_passport" name="member_passport" />
															<i><?php _e('e.g. passport, driving license, ID card etc.', CIP_TXTDOMAIN); ?></i><br/>
															<i><?php _e('Only jpg, jpeg, or png formats are valid. Max file size 8MB', CIP_TXTDOMAIN); ?></i>
														</div>
													</div>
													<div class="col text-center">
														<img src="<?php echo CIP_PLUGIN_FOLDER.'images/dummy-passport.png'; ?>" class="identification_image_passport" />
													</div>
												</div>

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

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

												<div class="row align-items-center pb-5">
													<div class="col">
														<div class="form-group">
															<label for="piece_paper_wallet_address"><?php _e('Upload your selfie', CIP_TXTDOMAIN); ?></label>
															<input type="file" class="form-control-file border" id="piece_paper_wallet_address" name="piece_paper_wallet_address" />
															<i><?php _e('Only jpg, jpeg, or png formats are valid. Max file size 8MB', CIP_TXTDOMAIN); ?></i>
															<br/>
															<ul>
																<li><?php _e('Take a selfie holding a plain piece of white paper with CSRNow.com, todays date, and Your CSR address clearly written on it.', CIP_TXTDOMAIN); ?></li>
																<li><?php _e('Hold your ID card in your hand, along with the piece of paper.', CIP_TXTDOMAIN); ?></li>
																<li><?php _e('Ensure that your face is completely visible and your hand does not obscure your ID card details.', CIP_TXTDOMAIN); ?></li>
															</ul>
														</div>
													</div>
													<div class="col text-center">
														<img src="<?php echo CIP_PLUGIN_FOLDER.'images/dummy-info-passport-hold.jpg'; ?>" class="img-fluid" />
													</div>
												</div>

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

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

												<div class="form-group">
													<label for="csrwalletaddress" class="col-form-label eth_address"><?php echo sprintf( __('Click verify to sign <a href="#" style="pointer-events: none;">%s</a> address in MetMask', CIP_TXTDOMAIN), $address ); ?></label>
													<small class="form-text text-muted"><?php _e('MetaMask will ask you to verify your wallet address. This action does not charge you any fees, nor does it make any changes to your CSR holdings.', CIP_TXTDOMAIN); ?></small>
													<p class="form_response"></p>
													<input type="hidden" name="action" value="sendLiftSHPendingAct" />
													<input type="hidden" name="_micro" value="<?php echo wp_create_nonce( $refAccount ); ?>" />
													<input type="hidden" name="thisId" value="<?php echo $_POST['thisId']; ?>" />
													<input type="hidden" name="thisAid" value="<?php echo $_POST['thisAid']; ?>" />
												</div>

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

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

												<div class="form-group form-check">
													<label class="form-check-label copy_all_checkbox eth_address">
														<input class="form-check-input" type="checkbox" name="confirm_lsh" value="1" style="margin-top: 0;"> <?php //_e('I confirm that I wish to Lift Security Hold from the <a href="#" style="pointer-events: none;">'.$address.'</a> and start receiving CSR distributions at my own risk', CIP_TXTDOMAIN); ?>
													</label>
												</div>

											</div>
											<input type="button" name="next" class="next action-button" value="Confirm" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
										</fieldset-->
									</form>
								</div>
							</div>
						</div>
					</div>
					<?php
					$html = ob_get_clean();
					$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
				}
			}else{
				$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email` FROM $tableTokenHolder WHERE `id` = ".$id." AND `email` = '".$refAccount."' AND `eth_address` = '".$address."' ");

				$allCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."'");
				$allIssuedCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND (`corp_approved` = 'Issued' OR `corp_approved` = 'Delivered' OR `corp_approved` = 'Saved CSR')");
				$allNoneIssuedCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND (`corp_approved` != 'Issued' AND `corp_approved` != 'Delivered' AND `corp_approved` != 'Saved CSR')");
				$allSHCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND `corp_approved` = 'Security Hold'");

				$updatedRecords = false;
				if( $getWalletRecord ){

					if( $allNoneIssuedCount == $allSHCount ){
						$out = array( "error" => 1, 'msg' => __('All record(s) are Security Hold', CIP_TXTDOMAIN) );
						echo wp_json_encode($out);
						exit;
					}

					if( $allCount != $allIssuedCount ){

						$getNoneIssuedDatas = $wpdb->get_results("SELECT `id`,`email`,`username`,`eth_address`,`corp_approved`,`notes_external` FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND ( `corp_approved` != 'Issued' AND `corp_approved` != 'Delivered' AND `corp_approved` != 'Saved CSR' )");

						if( $getNoneIssuedDatas ){

							foreach( $getNoneIssuedDatas as $getNoneIssuedData ){
								$externalNote = '| Distribution suspended until Security Hold lifted. |' . $getNoneIssuedData->notes_external;
								$externalNote = notes_trim_pipe( $externalNote );
								$data = array(
									'corp_approved'		=>	'Security Hold',
									'notes_external'	=>	$externalNote,
									'text_7'			=>	$getNoneIssuedData->corp_approved,
								);
								$updated = $wpdb->update( $tableTokenHolder, $data, [ 'id' => $getNoneIssuedData->id ] );

								if( $updated ){
									$updatedRecords = true;
								}
							}
							if( $updatedRecords ){
								$logs = sprintf( __('%s Set Security Hold CSR wallet address %s at %s', CIP_TXTDOMAIN), $refAccount, $address, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
								$out = array( "error" => 0, 'msg' => __('Record(s) updated to Security Hold', CIP_TXTDOMAIN) );
							}
						}

					}else{
						$out = array( "error" => 1, 'msg' => __('All record(s) are issued, not set to security hold', CIP_TXTDOMAIN) );
					}
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_sendLiftSHPendingAct', 'cip_sendLiftSHPendingAct_callback');
function cip_sendLiftSHPendingAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

	if( wp_verify_nonce( $_POST['_micro'], $refAccount ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableLSHPending = $wpdb->prefix.'csr_lsh_pending';
		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$decrypted_address_raw = base64_decode( $_POST['thisId'] );
		$address = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_address_raw);

		$decrypted_id_raw = base64_decode( $_POST['thisAid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_id_raw);

		$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email`,`username` FROM $tableTokenHolder WHERE `id` = ".$id." AND `email` = '".$refAccount."' AND `eth_address` = '".$address."' ");
		$allSHCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND `corp_approved` = 'Security Hold'");
		if( $allSHCount <= 0 ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. You don\'t have any security hold records',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( isset( $_POST['dataGetAddress'] ) && $_POST['dataGetAddress'] == 'yes' ){
			if( $getWalletRecord ){
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'thisAid' => $address );
			}
		}else if( isset( $_POST['dataValidateAddress'] ) && $_POST['dataValidateAddress'] == 'yes' && !empty( $_POST['returnedAddress'] ) ){
			if( $getWalletRecord && $_POST['returnedAddress'] == $address ){
				$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $address );
			}else{
				$out = array( "error" => 1, 'msg' => __('Invalid CSR wallet address', CIP_TXTDOMAIN) );
			}
		}else if( isset( $_POST['datagetSignatureMsg'] ) && $_POST['datagetSignatureMsg'] == 'yes' ){
			if( $getWalletRecord ){
				$eth_address = strtolower( $getWalletRecord->eth_address );
				$out = array( "error" => 0, 'msg' => 'I '.$refAccount.' confirm that I want to lift Security Hold on this address: '.$eth_address);
			}
		}else if( $getWalletRecord && !empty( $address ) && ( isset( $_POST['signature'] ) && !empty( $_POST['signature'] ) ) && $_POST['verifyingProcess'] == 'yes' ){ // sign verify
			$message = 'I '.$refAccount.' confirm that I want to lift Security Hold on this address: '.strtolower( $address );
			$verified = verifySignature('I '.$refAccount.' confirm that I want to lift Security Hold on this address: '.strtolower( $address ), $_POST['signature'], strtolower( $address ));
			if( $verified ){

				$ip_address = cip_get_client_ip();
				$logs = sprintf( __('MetaMask\'s signature & message of %s for Lift Security Hold. signature : %s, message : %s, ip : %s. At %s', CIP_TXTDOMAIN), $refAccount, $_POST['signature'], $message, $ip_address, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','member', $logs, true );
				$out = array( "error" => 0, 'msg' => __('Verification Sucess', CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
			}
		}else if( $getWalletRecord && isset( $_POST['returnedSignature'] ) && !empty( $_POST['returnedSignature'] ) ){
			$verified = verifySignature('I '.$refAccount.' confirm that I want to lift Security Hold on this address: '.strtolower( $address ), $_POST['returnedSignature'], strtolower( $address ));
			if( $verified ){
				$pendingLSHLists = $wpdb->get_var(" SELECT COUNT(id) FROM $tableLSHPending WHERE email = '".$refAccount."' AND status = 2 AND type = 'request' ORDER BY `id` DESC ");
				if( $pendingLSHLists ){
					$out = array( "error" => 1,'msg' => __('Your request already in pending for review',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				if( $_FILES['member_passport']['tmp_name'] != "" ){ //passport file

					if(!empty($_FILES["member_passport"]["name"]) && is_uploaded_file($_FILES['member_passport']['tmp_name']) ){

						$fileName = basename($_FILES["member_passport"]["name"]);

						$fileinfo = @getimagesize($_FILES["member_passport"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["member_passport"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Photo ID file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['member_passport']['tmp_name'];
						$member_passport = file_get_contents($_FILES['member_passport']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Photo ID file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}

				if( $_FILES['piece_paper_wallet_address']['tmp_name'] != "" ){ //piece_paper_wallet_address file

					if(!empty($_FILES["piece_paper_wallet_address"]["name"]) && is_uploaded_file($_FILES['piece_paper_wallet_address']['tmp_name']) ){

						$fileName = basename($_FILES["piece_paper_wallet_address"]["name"]);

						$fileinfo = @getimagesize($_FILES["piece_paper_wallet_address"]["tmp_name"]);

						$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
						$width = $fileinfo[0];
						$height = $fileinfo[1];

						$allowTypes = array('jpg','png','jpeg');

						if(!in_array($fileType, $allowTypes)){
							$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}else if (($_FILES["piece_paper_wallet_address"]["size"] > 8000000)){
							$out = array( "error" => 1,'msg' => __('Selfie file size exceeds 8MB',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$image = $_FILES['piece_paper_wallet_address']['tmp_name'];
						$piece_paper_wallet_address = file_get_contents($_FILES['piece_paper_wallet_address']['tmp_name']);
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Choose valid Selfie file format',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$data = array(
					'email'	=>	$refAccount,
					'username'	=>	$getWalletRecord->username,
					'eth_address'	=>	$address,
					'member_passport'	=>	$member_passport,
					'piece_paper_wallet_address'	=>	$piece_paper_wallet_address,
					'type'	=>	'request',
					'change_type'	=>	'add',
					'status'	=>	2,
					'reject_msg'	=>	'',
					'user_date'	=>	date_i18n( 'Y-m-d H:i:s' ),
					'sa_date'	=>	null,
				);
				$insert = $wpdb->insert( $tableLSHPending, $data );
				if( $insert ){
					$getSHRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE `email` = '".$refAccount."' AND `eth_address` = '".$address."' AND `corp_approved` = 'Security Hold'");
					if( $getSHRecords ){
						foreach( $getSHRecords as $getSHRecord ){
							$newExternalNotes = preg_replace(sprintf('/%s/', '| Distribution suspended until Security Hold lifted. |' ), '', $getSHRecord->notes_external);
							$newExternalNotes = '| Lift of Security Hold under review. |' . trim( $newExternalNotes );
							$newExternalNotes = notes_trim_pipe( $newExternalNotes );
							$data = array(
								'notes_external'	=>	$newExternalNotes,
							);
							$updatedNotes = $wpdb->update( $tableTokenHolder, $data, [ 'id' => $getSHRecord->id ] );
						}
					}
					$logs = sprintf( __('%s requested to Lifting Security Hold CSR wallet address %s, send to review at %s', CIP_TXTDOMAIN), $refAccount, $address, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( 0, 'profile', '','member', $logs, true  );
					$out = array( "error" => 0,'msg' => __('Your request to Lift Security Hold has been received. Please check back in 2 working days.',CIP_TXTDOMAIN) );
				}else{
					$out = array( "error" => 1,'msg' => __('Failed to sending Lifting Security Hold CSR wallet address for verification process.<br>Please contact to support',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1, 'msg' => __('Something went wrong. Verification failed', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action( 'wp_ajax_cip_reject_lsh_csraddress_act', 'cip_reject_lsh_csraddress_act_callback' );
function cip_reject_lsh_csraddress_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyRejectLSHCsrAddressyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableLSHPending = $wpdb->prefix.'csr_lsh_pending';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_id_raw);
		$getPendingData = $wpdb->get_row("SELECT * FROM $tableLSHPending WHERE id = ".$id." AND status != 1");
		if( $getPendingData ){
			$data = array('type' => 'rejected', 'status'	=>	0, 'reject_msg' => stripslashes( $_POST['rejectMsg'] ),'sa_date' => date_i18n( 'Y-m-d H:i:s') );
			$where = array('id'	=>	$getPendingData->id);
			$update = $wpdb->update( $tableLSHPending, $data, $where );
			if( $update ){
				$getSHRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE ( `username` = '".$getPendingData->username."' AND `username` IS NOT NULL AND `username` <> '' ) AND `eth_address` = '".$getPendingData->eth_address."' AND `corp_approved` = 'Security Hold'");
				if( $getSHRecords ){
					foreach( $getSHRecords as $getSHRecord ){
						$newExternalNotes = preg_replace(sprintf('/%s/', '| Lift of Security Hold under review. |' ), '', $getSHRecord->notes_external);
						$newExternalNotes = '| Distribution suspended until Security Hold lifted. |' . trim( $newExternalNotes );

						$newExternalNotes = notes_trim_pipe( $newExternalNotes );
						$data = array(
							'notes_external'	=>	$newExternalNotes,
						);
						$updatedNotes = $wpdb->update( $tableTokenHolder, $data, [ 'id' => $getSHRecord->id ] );
					}
				}
				$noticeMsg = sprintf( __('Your requested Lift Security Hold CSR address was rejected. The reason is : %s', CIP_TXTDOMAIN), stripslashes( $_POST['rejectMsg'] ) );
				$noticeData = array(
					"email"	=>	$getPendingData->email,
					"username"	=>	$getPendingData->username,
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$out = array( "error" => 0,'msg' => __('Rejected',CIP_TXTDOMAIN) );
				$user_id = get_current_user_id();
				$userData = get_user_by( 'id', $user_id );
				$logs = sprintf( __('Lift Security Hold CSR Address (%s) of %s rejected with reason(%s) by SA(%s) at %s', CIP_TXTDOMAIN),$getPendingData->eth_address, $getPendingData->email, $_POST['rejectMsg'], $userData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//4966
add_action( 'wp_ajax_cip_approved_lsh_csraddress_act', 'cip_approved_lsh_csraddress_act_callback' );
function cip_approved_lsh_csraddress_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyApprovedLSHCsrAddressyX_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableLSHPending = $wpdb->prefix.'csr_lsh_pending';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_REQUEST['thisid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_id_raw);
		$getPendingData = $wpdb->get_row("SELECT * FROM $tableLSHPending WHERE id = ".$id." AND status != 1");
		if( $getPendingData ){
			$data = array('status'	=>	1, 'reject_msg' => '','sa_date' => date_i18n( 'Y-m-d H:i:s') );
			$where = array('id'	=>	$getPendingData->id);
			$update = $wpdb->update( $tableLSHPending, $data, $where );
			if( $update ){
				$user_id = get_current_user_id();
				$userData = get_user_by( 'id', $user_id );
				$isUpdateLSH = false;
				$getLSHRecords = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE ( `username` = '".$getPendingData->username."' AND `username` IS NOT NULL AND `username` <> '' ) AND `eth_address` = '".$getPendingData->eth_address."' AND `corp_approved` = 'Security Hold'");
				if( $getLSHRecords ){
					foreach( $getLSHRecords as $getLSHRecord ){
						$newExternalNotes = preg_replace(sprintf('/%s/', '| Lift of Security Hold under review. |' ), '', $getLSHRecord->notes_external);
						$newExternalNotes = notes_trim_pipe( $newExternalNotes );
						$prevCorpStatus = $getLSHRecord->text_7;
						if($prevCorpStatus == "" || $prevCorpStatus == NULL)
						{$prevCorpStatus = $getLSHRecord->corp_approved;}
						$data = array(
							'corp_approved'		=>	$prevCorpStatus,
							'notes_external'	=>	$newExternalNotes,
							'text_7'			=>	null,
							'last_update'		=>	date_i18n( 'Y-m-d H:i:s' ),
						);
						$updatedLSH = $wpdb->update( $tableTokenHolder, $data, [ 'id' => $getLSHRecord->id ] );
						if( $updatedLSH ){
							$isUpdateLSH = true;
						}
					}
				}

				$out = array( "error" => 0,'msg' => __('Approved',CIP_TXTDOMAIN) );
				if( $isUpdateLSH ){
					$logs = sprintf( __('Lift Security Hold CSR address %s is approved of %s by SA(%s) at %s', CIP_TXTDOMAIN), $getPendingData->eth_address, $getPendingData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );

					$noticeMsg = __('Your requested Lift Security Hold CSR address is approved.', CIP_TXTDOMAIN);
					$noticeData = array(
						"email"	=>	$getPendingData->email,
						"username"	=>	$getPendingData->username,
						"notice"	=>	$noticeMsg,
						"status"	=>	1,
						"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
					);
					$wpdb->insert( $tableCipNotice, $noticeData );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
//5690 KYC
function getCountriesDropDown( $selected = '', $value = false ){
	$options = "";
	$GF_Field_Address = new GF_Field_Address();
	$countries = $GF_Field_Address->get_countries();
	$cipDisabledCountries = get_option( 'cipDisabledCountries' );
	$removeCountriesList = maybe_unserialize( $cipDisabledCountries );
	if( $countries ){
		if( $value ){
			foreach( $countries as $listcountry ){
				if( $listcountry == $selected ){
					$options = $listcountry;
				}
			}
		}else{
			$options = "<option value=''>Select</option>";
			foreach( $countries as $listcountry ){
				if( !in_array( $listcountry, $removeCountriesList ) ){
					$options .= '<option value="'.$listcountry.'" '.selected( $selected, $listcountry, false ).' >'.$listcountry.'</option>';
				}
			}
		}
	}
	/* global $wpdb;
	$tableCountries = $wpdb->prefix.'countries';
	if( $value ){
		$getCountries = $wpdb->get_row("SELECT * FROM $tableCountries WHERE `is_active` = 1 AND `id` = $selected ORDER BY `country_name` ASC");
		$options = $getCountries->country_name;
	}else{
		$options = "<option value=''>Select</option>";
		$getCountries = $wpdb->get_results("SELECT * FROM $tableCountries WHERE `is_active` = 1 ORDER BY `country_name` ASC");
		if( $getCountries ){
			foreach( $getCountries as $country ){
				$options .= "<option value='".$country->id."' ".selected( $selected, $country->id, false )." >".$country->country_name."</option>";
			}
		}
	} */
	return $options;
}
function getStatesDropDown( $countryCode = '', $selected = '', $value = false ){
	global $wpdb;
	$tableStates = $wpdb->prefix.'states';
	if( $value ){
		$getStates = $wpdb->get_row("SELECT * FROM $tableStates WHERE `country_id` = $countryCode AND `id` = $selected ORDER BY `name` ASC");
		$options = $getStates->name;
	}else{
		$options = "<option value=''>Select</option>";
		if( !empty( $countryCode ) ){
			$getStates = $wpdb->get_results("SELECT * FROM $tableStates WHERE `country_id` = $countryCode ORDER BY `name` ASC");
			if( $getStates ){
				foreach( $getStates as $state ){
					$options .= "<option value='".$state->id."' ".selected( $selected, $state->id, false ).">".$state->name."</option>";
				}
			}
		}
	}
	return $options;
}
function getCitiesDropDown( $stateCode = '', $selected = '', $value = false ){
	global $wpdb;
	$tableCities = $wpdb->prefix.'cities';
	if( $value ){
		$getCities = $wpdb->get_row("SELECT * FROM $tableCities WHERE `state_id` = $stateCode AND `id` = $selected ORDER BY `name` ASC");
		$options = $getCities->name;
	}else{
		$options = "<option value=''>Select</option>";
		if( !empty( $stateCode ) ){
			$getCities = $wpdb->get_results("SELECT * FROM $tableCities WHERE `state_id` = $stateCode ORDER BY `name` ASC");
			if( $getCities ){
				foreach( $getCities as $city ){
					$options .= "<option value='".$city->id."' ".selected( $selected, $city->id, false ).">".$city->name."</option>";
				}
			}
		}
	}
	return $options;
}
add_action( 'wp_ajax_getStatesAction', 'cip_getStatesAction_callback' );
function cip_getStatesAction_callback(){
	$options = getStatesDropDown( $_POST['country'] );
	$out = array( "error" => 0, 'options' => $options );
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_getCitiesAction', 'cip_getCitiesAction_callback' );
function cip_getCitiesAction_callback(){
	$options = getCitiesDropDown( $_POST['state'] );
	$out = array( "error" => 0, 'options' => $options );
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_member_kyc_account_type_save', 'member_kyc_account_type_save_callback' );
function member_kyc_account_type_save_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCIP_KYCACCOUNTTYPESAVE_CIPyX_' ) && ( current_user_can( 'member' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$checkHasData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $current_user->user_email ."'");
		$account_type = 'individual';
		if( $_POST['account_type'] == 'business' ){
			$account_type = 'business';
		}
		if( !$checkHasData ){
			$insertRow = $wpdb->insert( $tableKyc, ['account_type' => $account_type, 'email' => $current_user->user_email, '_date'	=>	date_i18n( 'Y-m-d H:i:s' ), 'current_step' => '1' ] );
			if( $insertRow ){
				$out = array( "error" => 0,'msg' => __('Account type saved',CIP_TXTDOMAIN) );
			}
		}else if( $checkHasData ){
			$update = $wpdb->update( $tableKyc, ['account_type' => $account_type, 'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ), 'current_step' => '1', 'is_first_step' => NULL ], [ 'id' => $checkHasData->id ] );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Account type saved',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cipMemberKycSubmitAct', 'cipMemberKycSubmitAct_callback' );
function cipMemberKycSubmitAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPMemberSUbmitKycCIP_' ) && ( current_user_can( 'member' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$checkHasData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $current_user->user_email ."'");
		if( !$checkHasData ){
			$insertRow = $wpdb->insert( $tableKyc, ['email' => $current_user->user_email, '_date'	=>	date_i18n( 'Y-m-d H:i:s' ), 'current_step' => '1' ] );
		}
		$whereData = array( 'email' => $current_user->user_email );
		$status = $checkHasData->status;
		$reject_steps = $checkHasData->reject_steps;
		$approve_steps = $checkHasData->approve_steps;

		if( $_POST['step'] == 'account_type' ){
			$updateData = array(
				'is_first_step'	=>	1,
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'1',
				'status'		=>	$status,
				'reject_steps'	=>	$reject_steps,
				'approve_steps'	=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			$out = array( "error" => 0,'msg' => __('Saved',CIP_TXTDOMAIN) );
		}else if( $_POST['step'] == 2 ){
			$id_have_expiry = ( $_POST['id_have_expiry'] == 1 ) ? 1 : null;
			$idcard_passport_expiry = ( $id_have_expiry == 1 ) ? $_POST['idcard_passport_expiry'] : null;
			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('1', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('1', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$dob = "";
			$dobError = true;
			try {
				if( DateTime::createFromFormat('d/m/Y', $_POST['dob']) !== false ){
					$dobObj = DateTime::createFromFormat('d/m/Y', $_POST['dob']);
					$dob = $dobObj->format('d/m/Y');
					$diff = $dobObj->diff(new DateTime());
					if ($diff->y < 18) {
						$out = array( "error" => 1,'msg' => __('Date of birth must be 18 years old.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$dobError = false;
				}
			} catch (\Throwable $th) {
				$dob = "";
			}
			if( $dobError ){
				$out = array( "error" => 1,'msg' => __('Invalid Date of Birth.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$updateData = array(
				'is_first_step'				=>	NULL,
				'firstname'					=>	$_POST['firstname'],
				'lastname'					=>	$_POST['lastname'],
				'dob'						=>	$_POST['dob'],
				'country'					=>	stripslashes( $_POST['country'] ),
				'state'						=>	stripslashes( $_POST['state'] ),
				'city'						=>	stripslashes( $_POST['city'] ),
				'postal_code'				=>	$_POST['postal_code'],
				'address'					=>	stripslashes( $_POST['address'] ),
				'street_address'			=>	stripslashes( $_POST['street_address'] ),
				// 'gender'					=>	$_POST['gender'],
				// 'nationality'			=>	$_POST['nationality'],
				// 'idcard_passport_number'	=>	$_POST['idcard_passport_number'],
				// 'id_have_expiry'			=>	$id_have_expiry,
				// 'idcard_passport_expiry'	=>	$idcard_passport_expiry,
				'lastupdate'				=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'				=>	'2',
				'status'					=>	$status,
				'reject_steps'				=>	$reject_steps,
				'approve_steps'				=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );

			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 3 ){
			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('2', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('2', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$id_no_have_expiry = ( $_POST['id_no_have_expiry'] == 1 ) ? 1 : null;
			$id_no_have_issue_date = ( $_POST['id_no_have_issue_date'] == 1 ) ? 1 : null;
			// $idcard_passport_expiry = ( $id_no_have_expiry == 1 ) ? $_POST['idcard_passport_expiry'] : null;
			if(!$id_no_have_issue_date){
				$issue_date = "";
				$issueDateError = true;
				try {
					if( DateTime::createFromFormat('d/m/Y', $_POST['issue_date']) !== false ){
						$dateObj = DateTime::createFromFormat('d/m/Y', $_POST['issue_date']);
						$issue_date = $dateObj->format('d/m/Y');
						$current_date = new DateTime();
						if( $dateObj > $current_date ){
							$out = array( "error" => 1,'msg' => __('You need to enter a date which was in the past.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$issueDateError = false;
					}
				} catch (\Throwable $th) {
					$issue_date = "";
				}
				if( $issueDateError ){
					$out = array( "error" => 1,'msg' => __('Invalid issue date.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
			if( !$id_no_have_expiry ){
				$expiration_date = "";
				$expirationDateError = true;
				try {
					if( DateTime::createFromFormat('d/m/Y', $_POST['expiration_date']) !== false ){
						$dateObj = DateTime::createFromFormat('d/m/Y', $_POST['expiration_date']);
						$expiration_date = $dateObj->format('d/m/Y');
						$current_date = new DateTime();

						if( $dateObj < $current_date ){
							$out = array( "error" => 1,'msg' => __('<b>Expiration Date</b><br/>You need to enter a date which will be in the future.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$issueDateObj = DateTime::createFromFormat('d/m/Y', $_POST['issue_date']);
						if( $issueDateObj > $dateObj ){
							$out = array( "error" => 1,'msg' => __('Expiration date can\'t be before issue date',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

						$expirationDateError = false;
					}
				} catch (\Throwable $th) {
					$expiration_date = "";
				}
				if( $expirationDateError ){
					$out = array( "error" => 1,'msg' => __('Invalid expiration date.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
			$updateData = array(
				'is_first_step'				=>	NULL,
				'nationality'				=>	$_POST['nationality'],
				'id_no_have_issue_date'		=>	$id_no_have_issue_date,
				'id_no_have_expiry'			=>	$id_no_have_expiry,
				'document_type'				=>	$_POST['document_type'],
				'document_number'			=>	$_POST['document_number'],
				'issuing_country'			=>	$_POST['issuing_country'],
				'issue_date'				=>	$_POST['issue_date'],
				'expiration_date'			=>	$_POST['expiration_date'],
				'lastupdate'				=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'				=>	'3',
				'status'					=>	$status,
				'reject_steps'				=>	$reject_steps,
				'approve_steps'				=>	$approve_steps,
			);


			$user_id = get_current_user_id();
			$uploadDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id;
			if (!file_exists( $uploadDir )) {
				mkdir( $uploadDir , 0755, true);
			}
			$IndexdDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id.'/index.php';
			if(!file_exists( $IndexdDir )){
				$newFileContent = '<?php // Silence is golden.';
				file_put_contents($IndexdDir, $newFileContent);
			}
			$documentError = false;
			$countDocuments = count( array_filter($_FILES['identification_document']['name']) );
			if( $countDocuments > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 document files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->identification_document_1 ) && empty( $checkHasData->identification_document_2 ) && empty( $checkHasData->identification_document_3 ) && $_FILES['identification_document']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Document is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $countDocuments <= 0 ){
					if( !empty( $checkHasData->identification_document_1 ) && file_exists( $uploadDir.'/'.$checkHasData->identification_document_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->identification_document_2 ) && file_exists( $uploadDir.'/'.$checkHasData->identification_document_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->identification_document_3 ) && file_exists( $uploadDir.'/'.$checkHasData->identification_document_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Document is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $countDocuments >= 1 ){
				for( $i=0; $i < $countDocuments; $i++ ){
					if( $_FILES['identification_document']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["identification_document"]["name"][$i]) && is_uploaded_file($_FILES['identification_document']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["identification_document"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError = true;
								$out = array( "error" => 1,'msg' => __('Choose valid document file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["identification_document"]["size"][$i] > 10000000)){
								$documentError = true;
								$out = array( "error" => 1,'msg' => __('document file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError = true;
						$out = array( "error" => 1,'msg' => __('Choose valid document file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}

				if( !$documentError ){
					$fileCount = 1;
					$updateData[ 'identification_document_1' ] = null;
					$updateData[ 'identification_document_2' ] = null;
					$updateData[ 'identification_document_3' ] = null;

					$filePatternDoc1 = $uploadDir."/identification_document_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/identification_document_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/identification_document_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $countDocuments; $i++ ){
						if( $_FILES['identification_document']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["identification_document"]["name"][$i]) && is_uploaded_file($_FILES['identification_document']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['identification_document']['tmp_name'][$i];
								$ext = pathinfo($_FILES['identification_document']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'identification_document_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'identification_document_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 4 ){

			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('3', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('3', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$document_date = "";
			$documentDateError = true;
			try {
				if( DateTime::createFromFormat('d/m/Y', $_POST['document_date']) !== false ){
					$dateObj = DateTime::createFromFormat('d/m/Y', $_POST['document_date']);
					$document_date = $dateObj->format('d/m/Y');

					$currentDatesObj = new DateTime();

					$interval = $dateObj->diff($currentDatesObj)->format("%r%a");
					if( $dateObj > $currentDatesObj ){
						$out = array( "error" => 1,'msg' => __('Document issue date cannot be in the future.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $interval > 90 || $interval < 0 ){
						$out = array( "error" => 1,'msg' => __('Document issue date cannot be older than 90 days.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$documentDateError = false;
				}
			} catch (\Throwable $th) {
				$document_date = "";
			}
			if( $documentDateError ){
				$out = array( "error" => 1,'msg' => __('Invalid document date.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$updateData = array(
				'is_first_step'			=>	NULL,
				'document_proof'		=>	$_POST['document_proof'],
				'document_date'			=>	$_POST['document_date'],
				'lastupdate'			=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'			=>	'4',
				'status'				=>	$status,
				'reject_steps'			=>	$reject_steps,
				'approve_steps'			=>	$approve_steps,
			);

			$user_id = get_current_user_id();
			$uploadDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id;
			if (!file_exists( $uploadDir )) {
				mkdir( $uploadDir , 0755, true);
			}
			$IndexdDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id.'/index.php';
			if(!file_exists( $IndexdDir )){
				$newFileContent = '<?php // Silence is golden.';
				file_put_contents($IndexdDir, $newFileContent);
			}
			$documentError = false;
			$countDocuments = count(array_filter($_FILES['proof_document']['name']));
			if( $countDocuments > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 document files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->proof_document_1 ) && empty( $checkHasData->proof_document_2 ) && empty( $checkHasData->proof_document_3 ) && $_FILES['proof_document']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Document is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $countDocuments <= 0 ){
					if( !empty( $checkHasData->proof_document_1 ) && file_exists( $uploadDir.'/'.$checkHasData->proof_document_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->proof_document_2 ) && file_exists( $uploadDir.'/'.$checkHasData->proof_document_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->proof_document_3 ) && file_exists( $uploadDir.'/'.$checkHasData->proof_document_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Document is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $countDocuments >= 1 ){
				for( $i=0; $i < $countDocuments; $i++ ){
					if( $_FILES['proof_document']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["proof_document"]["name"][$i]) && is_uploaded_file($_FILES['proof_document']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["proof_document"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError = true;
								$out = array( "error" => 1,'msg' => __('Choose valid document file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["proof_document"]["size"][$i] > 10000000)){
								$documentError = true;
								$out = array( "error" => 1,'msg' => __('document file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError = true;
						$out = array( "error" => 1,'msg' => __('Choose valid document file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
				if( !$documentError ){
					$fileCount = 1;
					$updateData[ 'proof_document_1' ] = null;
					$updateData[ 'proof_document_2' ] = null;
					$updateData[ 'proof_document_3' ] = null;
					$filePatternDoc1 = $uploadDir."/proof_document_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/proof_document_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/proof_document_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $countDocuments; $i++ ){
						if( $_FILES['proof_document']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["proof_document"]["name"][$i]) && is_uploaded_file($_FILES['proof_document']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['proof_document']['tmp_name'][$i];
								$ext = pathinfo($_FILES['proof_document']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'proof_document_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'proof_document_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 5 ){
			$user_id = get_current_user_id();
			$updateData = array(
				'is_first_step'					=>	NULL,
				'politically_exposed_person'	=>	$_POST['politically_exposed_person'],
				'consent_my_data_share'			=>	$_POST['consent_my_data_share'],
				'confirm_correct_info'			=>	$_POST['confirm_correct_info'],
				'lastupdate'					=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'					=>	'4',
				'status'						=>	'pending',
				'reject_steps'					=>	null,
				'approve_steps'					=>	null
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$logs = sprintf( __('KYC submitted by %s at %s.', CIP_TXTDOMAIN), $checkHasData->email, date_i18n('d/m/Y H:i A') );
				$userData = wp_get_current_user();
				$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '".$userData->user_email."'");
				// create_cip_logs_entery( 0, 'kyc', '','member', $logs, true  );
				kyc_customize_logs_function('member', 'KYC', $getKycData,'',$_FILES);
				$noticeMsg = __('Your KYC is submitted and it will be reviewed', CIP_TXTDOMAIN);
				$noticeData = array(
					"email"		=>	$checkHasData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$out = array( "error" => 0,'msg' => __('You have successfully submitted your KYC which will be reviewed by support within 3 working days.',CIP_TXTDOMAIN), 'dashboard_url' => get_permalink( 6630 ) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_nopriv_cipMemberKybSubmitAct', 'nopriv_cipMemberKybSubmitAct_callback' );
function nopriv_cipMemberKybSubmitAct_callback(){
	$out = array( "error" => 1,'msg' => __('You are logged out. Please login again and try again.',CIP_TXTDOMAIN) );
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cipMemberKybSubmitAct', 'cipMemberKybSubmitAct_callback' );
function cipMemberKybSubmitAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPMemberSUbmitKybCIP_' ) && ( current_user_can( 'member' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$checkHasData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '". $current_user->user_email ."'");
		if( !$checkHasData ){
			$insertRow = $wpdb->insert( $tableKyc, ['account_type' => 'business', 'email' => $current_user->user_email, '_date'	=>	date_i18n( 'Y-m-d H:i:s' ), 'current_step' => '1' ] );
		}
		$whereData = array( 'email' => $current_user->user_email );
		$status = $checkHasData->status;
		$reject_steps = $checkHasData->reject_steps;
		$approve_steps = $checkHasData->approve_steps;
		if( $_POST['step'] == 'account_type' ){

			$updateData = array(
				'is_first_step'	=>	1,
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'1',
				'status'		=>	$status,
				'reject_steps'	=>	$reject_steps,
				'approve_steps'	=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			$out = array( "error" => 0,'msg' => __('Saved',CIP_TXTDOMAIN) );
		}else if( $_POST['step'] == 2 ){
			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('2', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('2', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$updateData = array(
				'is_first_step'						=>	NULL,
				'business_name'						=>	stripslashes( $_POST['business_name'] ),
				'business_registration_country'		=>	stripslashes( $_POST['business_registration_country'] ),
				'business_registration_number'		=>	stripslashes( $_POST['business_registration_number'] ),
				'business_type_of_business'			=>	stripslashes( $_POST['business_type_of_business'] ),
				'business_nature_of_your_business'	=>	stripslashes( $_POST['business_nature_of_your_business'] ),
				'lastupdate'						=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'						=>	'3',
				'status'							=>	$status,
				'reject_steps'						=>	$reject_steps,
				'approve_steps'						=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );

			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 3 ){
			if( !empty( $_POST['business_company_website'] ) && !filter_var($_POST['business_company_website'], FILTER_VALIDATE_URL) ){
				$out = array( "error" => 1,'msg' => __('Company website url is not a valid format',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('3', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('3', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$business_same_as_registered_address = ( $_POST['business_same_as_registered_address'] == 1 ) ? 1 : 0;
			$updateData = array(
				'is_first_step'											=>	NULL,
				'business_registered_address'							=>	$_POST['business_registered_address'],
				'business_registered_address_line_2'					=>	$_POST['business_registered_address_line_2'],
				'business_registered_city'								=>	$_POST['business_registered_city'],
				'business_registered_state'								=>	$_POST['business_registered_state'],
				'business_registered_postal_code'						=>	$_POST['business_registered_postal_code'],
				'business_registered_country'							=>	stripslashes( $_POST['business_registered_country'] ),
				'business_same_as_registered_address'					=>	$business_same_as_registered_address,
				'business_operating_address'							=>	$_POST['business_operating_address'],
				'business_operating_address_line_2'						=>	$_POST['business_operating_address_line_2'],
				'business_operating_city'								=>	$_POST['business_operating_city'],
				'business_operating_state'								=>	$_POST['business_operating_state'],
				'business_operating_postal_code'						=>	$_POST['business_operating_postal_code'],
				'business_operating_country'							=>	stripslashes( $_POST['business_operating_country'] ),
				'business_contact_dial_code'							=>	$_POST['business_contact_dial_code'],
				'business_contact_country'								=>	$_POST['business_contact_country'],
				'business_contact_number'								=>	$_POST['business_contact_number'],
				'business_company_website'								=>	$_POST['business_company_website'],
				'business_aware_of_any_sanctions'						=>	$_POST['business_aware_of_any_sanctions'],
				'business_undergone_any_external_audits'				=>	$_POST['business_undergone_any_external_audits'],
				'business_business_involved_in_any_money_laundering'	=>	$_POST['business_business_involved_in_any_money_laundering'],
				'business_received_any_penalties'						=>	$_POST['business_received_any_penalties'],
				'lastupdate'											=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'											=>	'4',
				'status'												=>	$status,
				'reject_steps'											=>	$reject_steps,
				'approve_steps'											=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 4 ){
			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('4', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('4', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$business_director_details_same_as_owner = ( $_POST['business_director_details_same_as_owner'] == 1 ) ? 1 : 0;
			$updateData = array(
				'is_first_step'									=>	NULL,
				'business_director_first_name'					=>	$_POST['business_director_first_name'],
				'business_director_last_name'					=>	$_POST['business_director_last_name'],
				'business_director_dob'							=>	$_POST['business_director_dob'],
				'business_director_address'						=>	$_POST['business_director_address'],
				'business_director_address_line_2'				=>	$_POST['business_director_address_line_2'],
				'business_director_city'						=>	$_POST['business_director_city'],
				'business_director_state'						=>	$_POST['business_director_state'],
				'business_director_postal_code'					=>	$_POST['business_director_postal_code'],
				'business_director_country'						=>	stripslashes( $_POST['business_director_country'] ),
				'business_director_person_politically_exposed'	=>	$_POST['business_director_person_politically_exposed'],
				'business_director_details_same_as_owner'		=>	$business_director_details_same_as_owner,
				'business_owner_first_name'						=>	$_POST['business_owner_first_name'],
				'business_owner_last_name'						=>	$_POST['business_owner_last_name'],
				'business_owner_dob'							=>	$_POST['business_owner_dob'],
				'business_owner_address'						=>	$_POST['business_owner_address'],
				'business_owner_address_line_2'					=>	$_POST['business_owner_address_line_2'],
				'business_owner_city'							=>	$_POST['business_owner_city'],
				'business_owner_state'							=>	$_POST['business_owner_state'],
				'business_owner_postal_code'					=>	$_POST['business_owner_postal_code'],
				'business_owner_country'						=>	stripslashes( $_POST['business_owner_country'] ),
				'business_owner_person_politically_exposed'		=>	$_POST['business_owner_person_politically_exposed'],
				'lastupdate'									=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'									=>	'5',
				'status'										=>	$status,
				'reject_steps'									=>	$reject_steps,
				'approve_steps'									=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 5 ){

			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('5', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('5', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$updateData = array(
				'is_first_step'			=>	NULL,
				'lastupdate'			=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'			=>	'5',
				'status'				=>	$status,
				'reject_steps'			=>	$reject_steps,
				'approve_steps'			=>	$approve_steps,
			);

			$user_id = get_current_user_id();
			$uploadDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id;
			if (!file_exists( $uploadDir )) {
				mkdir( $uploadDir , 0755, true);
			}
			$IndexdDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id.'/index.php';
			if(!file_exists( $IndexdDir )){
				$newFileContent = '<?php // Silence is golden.';
				file_put_contents($IndexdDir, $newFileContent);
			}
			//Certificate of Incorporation/Registration of your company
			$documentError_1 = false;
			$count_business_certificate_of_incorporation = count(array_filter($_FILES['business_certificate_of_incorporation']['name']));
			if( $count_business_certificate_of_incorporation > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 Certificate of Incorporation/Registration of your company files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->business_certificate_of_incorporation_1 ) && empty( $checkHasData->business_certificate_of_incorporation_2 ) && empty( $checkHasData->business_certificate_of_incorporation_3 ) && $_FILES['business_certificate_of_incorporation']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Certificate of Incorporation/Registration of your company is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $count_business_certificate_of_incorporation <= 0 ){
					if( !empty( $checkHasData->business_certificate_of_incorporation_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_certificate_of_incorporation_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_certificate_of_incorporation_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_certificate_of_incorporation_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_certificate_of_incorporation_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_certificate_of_incorporation_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Certificate of Incorporation/Registration of your company is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_certificate_of_incorporation >= 1 ){
				for( $i=0; $i < $count_business_certificate_of_incorporation; $i++ ){
					if( $_FILES['business_certificate_of_incorporation']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["business_certificate_of_incorporation"]["name"][$i]) && is_uploaded_file($_FILES['business_certificate_of_incorporation']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["business_certificate_of_incorporation"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError_1 = true;
								$out = array( "error" => 1,'msg' => __('Choose valid certificate of incorporation/registration of your company file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["business_certificate_of_incorporation"]["size"][$i] > 10000000)){
								$documentError_1 = true;
								$out = array( "error" => 1,'msg' => __('Certificate of Incorporation/Registration of your company file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError_1 = true;
						$out = array( "error" => 1,'msg' => __('Choose valid certificate of incorporation/registration of your company file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			//Shareholder Certificate or Proof of Ownership
			$documentError_2 = false;
			$count_business_shareholder_certificate = count(array_filter($_FILES['business_shareholder_certificate']['name']));
			if( $count_business_shareholder_certificate > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 shareholder certificate or proof of ownership files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->business_shareholder_certificate_1 ) && empty( $checkHasData->business_shareholder_certificate_2 ) && empty( $checkHasData->business_shareholder_certificate_3 ) && $_FILES['business_shareholder_certificate']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('shareholder certificate or proof of ownership is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $count_business_shareholder_certificate <= 0 ){
					if( !empty( $checkHasData->business_shareholder_certificate_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_shareholder_certificate_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_shareholder_certificate_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_shareholder_certificate_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_shareholder_certificate_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_shareholder_certificate_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Shareholder certificate or proof of ownership is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_shareholder_certificate >= 1 ){
				for( $i=0; $i < $count_business_shareholder_certificate; $i++ ){
					if( $_FILES['business_shareholder_certificate']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["business_shareholder_certificate"]["name"][$i]) && is_uploaded_file($_FILES['business_shareholder_certificate']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["business_shareholder_certificate"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError_2 = true;
								$out = array( "error" => 1,'msg' => __('Choose valid Shareholder Certificate or Proof of Ownership file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["business_shareholder_certificate"]["size"][$i] > 10000000)){
								$documentError_2 = true;
								$out = array( "error" => 1,'msg' => __('Shareholder Certificate or Proof of Ownership file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError_2 = true;
						$out = array( "error" => 1,'msg' => __('Choose valid Shareholder Certificate or Proof of Ownership file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}


			//Proof of address of the Business
			$documentError_3 = false;
			$count_business_proof_address = count(array_filter($_FILES['business_proof_address']['name']));
			if( $count_business_proof_address > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 Proof of address of the Business files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->business_proof_address_1 ) && empty( $checkHasData->business_proof_address_2 ) && empty( $checkHasData->business_proof_address_3 ) && $_FILES['business_proof_address']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Proof of address of the Business is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $count_business_proof_address <= 0 ){
					if( !empty( $checkHasData->business_proof_address_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_proof_address_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_proof_address_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_proof_address_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_proof_address_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_proof_address_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Proof of address of the Business is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_proof_address >= 1 ){
				for( $i=0; $i < $count_business_proof_address; $i++ ){
					if( $_FILES['business_proof_address']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["business_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_proof_address']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["business_proof_address"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError_3 = true;
								$out = array( "error" => 1,'msg' => __('Choose valid Proof of address of the Business file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["business_proof_address"]["size"][$i] > 10000000)){
								$documentError_3 = true;
								$out = array( "error" => 1,'msg' => __('Proof of address of the Business file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError_3 = true;
						$out = array( "error" => 1,'msg' => __('Choose valid Proof of address of the Business file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			//uploading to folders
			if( $count_business_certificate_of_incorporation >= 1 ){
				if( !$documentError_1 ){
					$fileCount = 1;
					$updateData[ 'business_certificate_of_incorporation_1' ] = null;
					$updateData[ 'business_certificate_of_incorporation_2' ] = null;
					$updateData[ 'business_certificate_of_incorporation_3' ] = null;
					$filePatternDoc1 = $uploadDir."/business_certificate_of_incorporation_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/business_certificate_of_incorporation_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/business_certificate_of_incorporation_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $count_business_certificate_of_incorporation; $i++ ){
						if( $_FILES['business_certificate_of_incorporation']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_certificate_of_incorporation"]["name"][$i]) && is_uploaded_file($_FILES['business_certificate_of_incorporation']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['business_certificate_of_incorporation']['tmp_name'][$i];
								$ext = pathinfo($_FILES['business_certificate_of_incorporation']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'business_certificate_of_incorporation_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'business_certificate_of_incorporation_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			if( $count_business_shareholder_certificate >= 1 ){
				if( !$documentError_2 ){
					$fileCount = 1;
					$updateData[ 'business_shareholder_certificate_1' ] = null;
					$updateData[ 'business_shareholder_certificate_2' ] = null;
					$updateData[ 'business_shareholder_certificate_3' ] = null;
					$filePatternDoc1 = $uploadDir."/business_shareholder_certificate_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/business_shareholder_certificate_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/business_shareholder_certificate_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $count_business_shareholder_certificate; $i++ ){
						if( $_FILES['business_shareholder_certificate']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_shareholder_certificate"]["name"][$i]) && is_uploaded_file($_FILES['business_shareholder_certificate']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['business_shareholder_certificate']['tmp_name'][$i];
								$ext = pathinfo($_FILES['business_shareholder_certificate']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'business_shareholder_certificate_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'business_shareholder_certificate_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			if( $count_business_proof_address >= 1 ){
				if( !$documentError_3 ){
					$fileCount = 1;
					$updateData[ 'business_proof_address_1' ] = null;
					$updateData[ 'business_proof_address_2' ] = null;
					$updateData[ 'business_proof_address_3' ] = null;
					$filePatternDoc1 = $uploadDir."/business_proof_address_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/business_proof_address_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/business_proof_address_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $count_business_proof_address; $i++ ){
						if( $_FILES['business_proof_address']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_proof_address']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['business_proof_address']['tmp_name'][$i];
								$ext = pathinfo($_FILES['business_proof_address']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'business_proof_address_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'business_proof_address_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 6 ){

			if( $status == 'reject' && !empty( $reject_steps ) ){
				$rejectStepsArr = explode(",", $reject_steps);
				if( ($key = array_search('5', $rejectStepsArr)) !== false ){
					unset($rejectStepsArr[$key]);
				}
				$reject_steps = implode(',', $rejectStepsArr );
			}
			if( $status == 'reject' && !empty( $approve_steps ) ){
				$approveStepsArr = explode(",", $approve_steps);
				if( ($key = array_search('5', $approveStepsArr)) !== false ){
					unset($approveStepsArr[$key]);
				}
				$approve_steps = implode(',', $approveStepsArr );
			}
			$updateData = array(
				'is_first_step'			=>	NULL,
				'lastupdate'			=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'			=>	'6',
				'status'				=>	$status,
				'reject_steps'			=>	$reject_steps,
				'approve_steps'			=>	$approve_steps,
			);

			$user_id = get_current_user_id();
			$uploadDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id;
			if (!file_exists( $uploadDir )) {
				mkdir( $uploadDir , 0755, true);
			}
			$IndexdDir = CIP_PLUGIN_BASE . '/uploaded_doc/'.$user_id.'/index.php';
			if(!file_exists( $IndexdDir )){
				$newFileContent = '<?php // Silence is golden.';
				file_put_contents($IndexdDir, $newFileContent);
			}
			//Business Owner
			//Passport or National ID
			$documentError_1 = false;
			$count_business_owner_passport_national_id = count(array_filter($_FILES['business_owner_passport_national_id']['name']));
			if( $count_business_owner_passport_national_id > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 Business Owner Passport or National ID files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->business_owner_passport_national_id_1 ) && empty( $checkHasData->business_owner_passport_national_id_2 ) && empty( $checkHasData->business_owner_passport_national_id_3 ) && $_FILES['business_owner_passport_national_id']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Business Owner Passport or National ID is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $count_business_owner_passport_national_id <= 0 ){
					if( !empty( $checkHasData->business_owner_passport_national_id_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_passport_national_id_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_owner_passport_national_id_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_passport_national_id_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_owner_passport_national_id_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_passport_national_id_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Business Owner Passport or National ID is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_owner_passport_national_id >= 1 ){
				for( $i=0; $i < $count_business_owner_passport_national_id; $i++ ){
					if( $_FILES['business_owner_passport_national_id']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["business_owner_passport_national_id"]["name"][$i]) && is_uploaded_file($_FILES['business_owner_passport_national_id']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["business_owner_passport_national_id"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError_1 = true;
								$out = array( "error" => 1,'msg' => __('Choose valid Business Owner Passport or National ID file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["business_owner_passport_national_id"]["size"][$i] > 10000000)){
								$documentError_1 = true;
								$out = array( "error" => 1,'msg' => __('Business Owner Passport or National ID file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError_1 = true;
						$out = array( "error" => 1,'msg' => __('Choose valid Business Owner Passport or National ID file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			//Business Owner
			//Proof of address
			$documentError_2 = false;
			$count_business_owner_proof_address = count(array_filter($_FILES['business_owner_proof_address']['name']));
			if( $count_business_owner_proof_address > 3 ){
				$out = array( "error" => 1,'msg' => __('Maximum 3 Business Owner Proof of address files are allowed.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$filesHaveInFolder = false;
			if( empty( $checkHasData->business_owner_proof_address_1 ) && empty( $checkHasData->business_owner_proof_address_2 ) && empty( $checkHasData->business_owner_proof_address_3 ) && $_FILES['business_owner_proof_address']['name'][0] == "" ){
				$out = array( "error" => 1,'msg' => __('Business Owner Proof of address is required.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}else{
				if( $count_business_owner_proof_address <= 0 ){
					if( !empty( $checkHasData->business_owner_proof_address_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_proof_address_1 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_owner_proof_address_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_proof_address_2 ) ){
						$filesHaveInFolder = true;
					}
					if( !empty( $checkHasData->business_owner_proof_address_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_owner_proof_address_3 ) ){
						$filesHaveInFolder = true;
					}
					if( !$filesHaveInFolder ){
						$out = array( "error" => 1,'msg' => __('Business Owner Proof of address is required.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_owner_proof_address >= 1 ){
				for( $i=0; $i < $count_business_owner_proof_address; $i++ ){
					if( $_FILES['business_owner_proof_address']['tmp_name'][$i] != "" ){

						if(!empty($_FILES["business_owner_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_owner_proof_address']['tmp_name'][$i]) ){

							$fileName = basename($_FILES["business_owner_proof_address"]["name"][$i]);
							$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
							$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

							if(!in_array($fileType, $allowTypes)){
								$documentError_2 = true;
								$out = array( "error" => 1,'msg' => __('Choose valid Business Owner Proof of address file format',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}else if (($_FILES["business_owner_proof_address"]["size"][$i] > 10000000)){
								$documentError_2 = true;
								$out = array( "error" => 1,'msg' => __('Business Owner Proof of address file size exceeds 10MB',CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
						}

					}else{
						$documentError_2 = true;
						$out = array( "error" => 1,'msg' => __('Choose valid Business Owner Proof of address file format',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
			}
			if( $count_business_owner_passport_national_id >= 1 ){
				if( !$documentError_1 ){
					$fileCount = 1;
					$updateData[ 'business_owner_passport_national_id_1' ] = null;
					$updateData[ 'business_owner_passport_national_id_2' ] = null;
					$updateData[ 'business_owner_passport_national_id_3' ] = null;
					$filePatternDoc1 = $uploadDir."/business_owner_passport_national_id_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/business_owner_passport_national_id_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/business_owner_passport_national_id_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $count_business_owner_passport_national_id; $i++ ){
						if( $_FILES['business_owner_passport_national_id']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_owner_passport_national_id"]["name"][$i]) && is_uploaded_file($_FILES['business_owner_passport_national_id']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['business_owner_passport_national_id']['tmp_name'][$i];
								$ext = pathinfo($_FILES['business_owner_passport_national_id']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'business_owner_passport_national_id_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'business_owner_passport_national_id_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}
			if( $count_business_owner_proof_address >= 1 ){
				if( !$documentError_2 ){
					$fileCount = 1;
					$updateData[ 'business_owner_proof_address_1' ] = null;
					$updateData[ 'business_owner_proof_address_2' ] = null;
					$updateData[ 'business_owner_proof_address_3' ] = null;
					$filePatternDoc1 = $uploadDir."/business_owner_proof_address_1.*";
					array_map( "unlink", glob( $filePatternDoc1 ) );
					$filePatternDoc2 = $uploadDir."/business_owner_proof_address_2.*";
					array_map( "unlink", glob( $filePatternDoc2 ) );
					$filePatternDoc3 = $uploadDir."/business_owner_proof_address_3.*";
					array_map( "unlink", glob( $filePatternDoc3 ) );
					for( $i=0; $i < $count_business_owner_proof_address; $i++ ){
						if( $_FILES['business_owner_proof_address']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_owner_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_owner_proof_address']['tmp_name'][$i]) ){

								$tmpFilePath = $_FILES['business_owner_proof_address']['tmp_name'][$i];
								$ext = pathinfo($_FILES['business_owner_proof_address']['name'][$i], PATHINFO_EXTENSION);
								$shortname = 'business_owner_proof_address_'.$fileCount.'.'.$ext;
								$filePath = $uploadDir."/" . $shortname;
								if(move_uploaded_file($tmpFilePath, $filePath)) {
									$updateData[ 'business_owner_proof_address_'.$fileCount ] = $shortname;
									$fileCount++;
								}
							}
						}
					}
				}
			}

			$business_director_details_same_as_owner = ( $_POST['business_director_details_same_as_owner'] == 1 ) ? 1 : 0;
			if( $business_director_details_same_as_owner != 1 ){
				//Director or Equivalent Person
				//Passport or National ID
				$documentError_3 = false;
				$count_business_director_passport_national_id = count(array_filter($_FILES['business_director_passport_national_id']['name']));
				if( $count_business_director_passport_national_id > 3 ){
					$out = array( "error" => 1,'msg' => __('Maximum 3 Director Passport or National ID files are allowed.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$filesHaveInFolder = false;
				if( empty( $checkHasData->business_director_passport_national_id_1 ) && empty( $checkHasData->business_director_passport_national_id_2 ) && empty( $checkHasData->business_director_passport_national_id_3 ) && $_FILES['business_director_passport_national_id']['name'][0] == "" ){
					$out = array( "error" => 1,'msg' => __('Director Passport or National ID is required.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}else{
					if( $count_business_director_passport_national_id <= 0 ){
						if( !empty( $checkHasData->business_director_passport_national_id_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_passport_national_id_1 ) ){
							$filesHaveInFolder = true;
						}
						if( !empty( $checkHasData->business_director_passport_national_id_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_passport_national_id_2 ) ){
							$filesHaveInFolder = true;
						}
						if( !empty( $checkHasData->business_director_passport_national_id_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_passport_national_id_3 ) ){
							$filesHaveInFolder = true;
						}
						if( !$filesHaveInFolder ){
							$out = array( "error" => 1,'msg' => __('Director Passport or National ID is required.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}
				if( $count_business_director_passport_national_id >= 1 ){
					for( $i=0; $i < $count_business_director_passport_national_id; $i++ ){
						if( $_FILES['business_director_passport_national_id']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_director_passport_national_id"]["name"][$i]) && is_uploaded_file($_FILES['business_director_passport_national_id']['tmp_name'][$i]) ){

								$fileName = basename($_FILES["business_director_passport_national_id"]["name"][$i]);
								$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
								$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

								if(!in_array($fileType, $allowTypes)){
									$documentError_3 = true;
									$out = array( "error" => 1,'msg' => __('Choose valid Director Passport or National ID file format',CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}else if (($_FILES["business_director_passport_national_id"]["size"][$i] > 10000000)){
									$documentError_3 = true;
									$out = array( "error" => 1,'msg' => __('Director Passport or National ID file size exceeds 10MB',CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
							}

						}else{
							$documentError_3 = true;
							$out = array( "error" => 1,'msg' => __('Choose valid Director Passport or National ID file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}
				//Director or Equivalent Person
				//Proof of address
				$documentError_4 = false;
				$count_business_director_proof_address = count(array_filter($_FILES['business_director_proof_address']['name']));
				if( $count_business_director_proof_address > 3 ){
					$out = array( "error" => 1,'msg' => __('Maximum 3 Director Proof of address files are allowed.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$filesHaveInFolder = false;
				if( empty( $checkHasData->business_director_proof_address_1 ) && empty( $checkHasData->business_director_proof_address_2 ) && empty( $checkHasData->business_director_proof_address_3 ) && $_FILES['business_director_proof_address']['name'][0] == "" ){
					$out = array( "error" => 1,'msg' => __('Director Proof of address is required.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}else{
					if( $count_business_director_proof_address <= 0 ){
						if( !empty( $checkHasData->business_director_proof_address_1 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_proof_address_1 ) ){
							$filesHaveInFolder = true;
						}
						if( !empty( $checkHasData->business_director_proof_address_2 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_proof_address_2 ) ){
							$filesHaveInFolder = true;
						}
						if( !empty( $checkHasData->business_director_proof_address_3 ) && file_exists( $uploadDir.'/'.$checkHasData->business_director_proof_address_3 ) ){
							$filesHaveInFolder = true;
						}
						if( !$filesHaveInFolder ){
							$out = array( "error" => 1,'msg' => __('Director Proof of address is required.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}
				if( $count_business_director_proof_address >= 1 ){
					for( $i=0; $i < $count_business_director_proof_address; $i++ ){
						if( $_FILES['business_director_proof_address']['tmp_name'][$i] != "" ){

							if(!empty($_FILES["business_director_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_director_proof_address']['tmp_name'][$i]) ){

								$fileName = basename($_FILES["business_director_proof_address"]["name"][$i]);
								$fileType = strtolower( pathinfo($fileName, PATHINFO_EXTENSION) );
								$allowTypes = array('jpg', 'png', 'jpeg', 'pdf');

								if(!in_array($fileType, $allowTypes)){
									$documentError_4 = true;
									$out = array( "error" => 1,'msg' => __('Choose valid Director Proof of address file format',CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}else if (($_FILES["business_director_proof_address"]["size"][$i] > 10000000)){
									$documentError_4 = true;
									$out = array( "error" => 1,'msg' => __('Director Proof of address file size exceeds 10MB',CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
							}

						}else{
							$documentError_4 = true;
							$out = array( "error" => 1,'msg' => __('Choose valid Director Proof of address file format',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}
				if( $count_business_director_passport_national_id >= 1 ){
					if( !$documentError_3 ){
						$fileCount = 1;
						$updateData[ 'business_director_passport_national_id_1' ] = null;
						$updateData[ 'business_director_passport_national_id_2' ] = null;
						$updateData[ 'business_director_passport_national_id_3' ] = null;
						$filePatternDoc1 = $uploadDir."/business_director_passport_national_id_1.*";
						array_map( "unlink", glob( $filePatternDoc1 ) );
						$filePatternDoc2 = $uploadDir."/business_director_passport_national_id_2.*";
						array_map( "unlink", glob( $filePatternDoc2 ) );
						$filePatternDoc3 = $uploadDir."/business_director_passport_national_id_3.*";
						array_map( "unlink", glob( $filePatternDoc3 ) );
						for( $i=0; $i < $count_business_director_passport_national_id; $i++ ){
							if( $_FILES['business_director_passport_national_id']['tmp_name'][$i] != "" ){

								if(!empty($_FILES["business_director_passport_national_id"]["name"][$i]) && is_uploaded_file($_FILES['business_director_passport_national_id']['tmp_name'][$i]) ){

									$tmpFilePath = $_FILES['business_director_passport_national_id']['tmp_name'][$i];
									$ext = pathinfo($_FILES['business_director_passport_national_id']['name'][$i], PATHINFO_EXTENSION);
									$shortname = 'business_director_passport_national_id_'.$fileCount.'.'.$ext;
									$filePath = $uploadDir."/" . $shortname;
									if(move_uploaded_file($tmpFilePath, $filePath)) {
										$updateData[ 'business_director_passport_national_id_'.$fileCount ] = $shortname;
										$fileCount++;
									}
								}
							}
						}
					}
				}
				if( $count_business_director_proof_address >= 1 ){
					if( !$documentError_4 ){
						$fileCount = 1;
						$updateData[ 'business_director_proof_address_1' ] = null;
						$updateData[ 'business_director_proof_address_2' ] = null;
						$updateData[ 'business_director_proof_address_3' ] = null;
						$filePatternDoc1 = $uploadDir."/business_director_proof_address_1.*";
						array_map( "unlink", glob( $filePatternDoc1 ) );
						$filePatternDoc2 = $uploadDir."/business_director_proof_address_2.*";
						array_map( "unlink", glob( $filePatternDoc2 ) );
						$filePatternDoc3 = $uploadDir."/business_director_proof_address_3.*";
						array_map( "unlink", glob( $filePatternDoc3 ) );
						for( $i=0; $i < $count_business_director_proof_address; $i++ ){
							if( $_FILES['business_director_proof_address']['tmp_name'][$i] != "" ){

								if(!empty($_FILES["business_director_proof_address"]["name"][$i]) && is_uploaded_file($_FILES['business_director_proof_address']['tmp_name'][$i]) ){

									$tmpFilePath = $_FILES['business_director_proof_address']['tmp_name'][$i];
									$ext = pathinfo($_FILES['business_director_proof_address']['name'][$i], PATHINFO_EXTENSION);
									$shortname = 'business_director_proof_address_'.$fileCount.'.'.$ext;
									$filePath = $uploadDir."/" . $shortname;
									if(move_uploaded_file($tmpFilePath, $filePath)) {
										$updateData[ 'business_director_proof_address_'.$fileCount ] = $shortname;
										$fileCount++;
									}
								}
							}
						}
					}
				}
			}
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$out = array( "error" => 0,'msg' => __('Data saved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}else if( $_POST['step'] == 7 ){
			$user_id = get_current_user_id();
			$updateData = array(
				'is_first_step'					=>	NULL,
				'consent_my_data_share'			=>	$_POST['consent_my_data_share'],
				'confirm_correct_info'			=>	$_POST['confirm_correct_info'],
				'lastupdate'					=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'					=>	'7',
				'status'						=>	'pending',
				'reject_steps'					=>	null,
				'approve_steps'					=>	null
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$logs = sprintf( __('KYB submitted by %s at %s.', CIP_TXTDOMAIN), $checkHasData->email, date_i18n('d/m/Y H:i A') );
				// create_cip_logs_entery( 0, 'kyb', '','member', $logs, true  );
				$userData = wp_get_current_user();
				$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE `email` = '".$userData->user_email."'");
				kyc_customize_logs_function( 'member', 'KYB', $getKycData, '',$_FILES);
				$noticeMsg = __('Your KYB is submitted and it will be reviewed', CIP_TXTDOMAIN);
				$noticeData = array(
					"email"		=>	$checkHasData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$out = array( "error" => 0,'msg' => __('You have successfully submitted your KYB which will be reviewed by support within 3 working days.',CIP_TXTDOMAIN), 'dashboard_url' => get_permalink( 6630 ) );
			}else{
				$out = array( "error" => 1,'msg' => __('Data is not saved. Please try again or contact support',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_drop_kyc_verification_act', 'drop_kyc_verification_act_callback' );
function drop_kyc_verification_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPDropKycCIPXy_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_POST['_microid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_kyc_CIP') ), '', $decrypted_id_raw);
		$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
		$type = "kyc";
		$type_txt = __("KYC", CIP_TXTDOMAIN);
		if( $getKycData ){
			if( $getKycData->account_type == 'business' ){
				$type = "kyb";
				$type_txt = __("KYB", CIP_TXTDOMAIN);
			}
			$userData = get_user_by('email', $getKycData->email);
			$whereData = array( 'email' => $getKycData->email );
			$reject_steps = "";
			$reject_steps_list = [];
			if( !empty( $_POST['dropSteps'][0] ) ){
				$reject_steps = implode( ',', $_POST['dropSteps'] );
				foreach( $_POST['dropSteps'] as $dropStep ){
					if( $type == 'kyb' ){
						$reject_steps_list[] = getKybStepsName( $dropStep );
					}else{
						$reject_steps_list[] = getKycStepsName( $dropStep );
					}
				}
			}
			$user_id = get_current_user_id();
			$updateData = array(
				'is_first_step'	=>	1,
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'0',
				'status'		=>	'dropped',
				'reject_steps'	=>	$reject_steps,
				'approve_steps'	=>	'',
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){

				$userData = wp_get_current_user();
				$logs = sprintf( __('%s dropped for %s by SA(%s) at %s. Dropped reason: %s. Reason: %s', CIP_TXTDOMAIN), $type_txt, $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A'), $_POST['drop_message'], implode( ', ',$reject_steps_list ) );
				// create_cip_logs_entery( 0, $type, '','sa', $logs, true  );
				kyc_customize_logs_function('sa', strtoupper($type), $getKycData,$logs);
				$noticeMsg = sprintf( __('Your %s is dropped. The reason is : %s. <a href="%s">View your KYC/KYB</a>', CIP_TXTDOMAIN), $type_txt, stripslashes( $_POST['drop_message'] ), getKycPageLink() );
				$noticeData = array(
					"email"		=>	$getKycData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$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 = __($type_txt .' status changed', CIP_TXTDOMAIN);
				$message = sprintf( __('<h2>Dear Member,</h2><h3>Your '.$type_txt.' has been dropped.</h3><p>Reason: %s</p><p>%s</p><p>You can check the status of your '.$type_txt.' 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>', CIP_TXTDOMAIN), stripslashes( $_POST['drop_message'] ), implode( ', ',$reject_steps_list ), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
				$htmlContent = kycMailTemplateHtmlRender( $message );
				if( get_email_send_toggle('kyc_status_change') == 1 ){
					wp_mail( $getKycData->email, $subject, $htmlContent );
				}
				$out = array( "error" => 0,'msg' => __($type_txt . ' dropped.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Something went wrong. '.$type_txt.' not dropped.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_reject_whole_kyc_verification_act', 'reject_whole_kyc_verification_act_callback' );
function reject_whole_kyc_verification_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPRejectWholeKycCIPXy_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_POST['_microid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_kyc_CIP') ), '', $decrypted_id_raw);
		$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
		$type = "kyc";
		$type_txt = __("KYC", CIP_TXTDOMAIN);
		if( $getKycData ){
			if( $getKycData->account_type == 'business' ){
				$type = "kyb";
				$type_txt = __("KYB", CIP_TXTDOMAIN);
			}
			$userData = get_user_by('email', $getKycData->email);
			$whereData = array( 'email' => $getKycData->email );
			$reject_steps = "1,2,3,4";
			if( $type == 'kyb' ){
				$reject_steps = "1,2,3,4,5";
			}
			$reject_steps_list = [];
			if( !empty( $_POST['dropSteps'][0] ) ){
				$reject_steps = implode( ',', $_POST['dropSteps'] );
				foreach( $_POST['dropSteps'] as $dropStep ){
					if( $type == 'kyb' ){
						$reject_steps_list[] = getKybStepsName( $dropStep );
					}else{
						$reject_steps_list[] = getKycStepsName( $dropStep );
					}
				}
			}
			$user_id = get_current_user_id();
			$updateData = array(
				'is_first_step'	=>	1,
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'0',
				'status'		=>	'reject',
				'reject_steps'	=>	$reject_steps,
				'approve_steps'	=>	'',
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){

				$userData = wp_get_current_user();
				$logs = sprintf( __($type_txt . ' rejected for %s by SA(%s) at %s. Rejection reason: %s. Steps: %s', CIP_TXTDOMAIN), $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A'), $_POST['rejection_message'], implode( ', ',$reject_steps_list ) );
				// create_cip_logs_entery( 0, $type, '','sa', $logs, true  );
				kyc_customize_logs_function('sa', strtoupper($type), $getKycData,$logs);
				$noticeMsg = sprintf( __('Your '.$type_txt.' is rejected. The reason is : %s. <br/><a href="%s">View your '.$type_txt.'</a>', CIP_TXTDOMAIN), stripslashes( $_POST['rejection_message'] ), getKycPageLink() );
				$noticeData = array(
					"email"		=>	$getKycData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$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 = __($type_txt . ' status changed', CIP_TXTDOMAIN);
				$message = sprintf( __('<h2>Dear Member,</h2><h3>Your '.$type_txt.' has been rejected.</h3><p>Reason: %s</p><p>%s</p><p>You can check the status of your '.$type_txt.' 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>', CIP_TXTDOMAIN), stripslashes( $_POST['rejection_message'] ), implode( ', ',$reject_steps_list ), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
				$htmlContent = kycMailTemplateHtmlRender( $message );
				if( get_email_send_toggle('kyc_status_change') == 1 ){
					wp_mail( $getKycData->email, $subject, $htmlContent );
				}
				$out = array( "error" => 0,'msg' => __($type_txt . ' rejected.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Something went wrong. '.$type_txt.' not rejected.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_approved_kyc_verification_act', 'approved_kyc_verification_act_callback' );
function approved_kyc_verification_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPApprovedKycCIPXy_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_POST['_microid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_kyc_CIP') ), '', $decrypted_id_raw);
		$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
		$type = "kyc";
		$type_txt = __("KYC", CIP_TXTDOMAIN);
		if( $getKycData ){
			if( $getKycData->account_type == 'business' ){
				$type = "kyb";
				$type_txt = __("KYB", CIP_TXTDOMAIN);
			}
			$userData = get_user_by('email', $getKycData->email);
			$whereData = array( 'email' => $getKycData->email );
			$user_id = get_current_user_id();
			$approve_steps = '1,2,3,4';
			if( $type == 'kyb' ){
				$approve_steps = '1,2,3,4,5';
			}
			$updateData = array(
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'0',
				'status'		=>	'approved',
				'reject_steps'	=>	'',
				'approve_steps'	=>	$approve_steps,
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){

				$userData = wp_get_current_user();
				$logs = sprintf( __($type_txt. ' approved for %s by SA(%s) at %s.', CIP_TXTDOMAIN), $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
				// create_cip_logs_entery( 0, $type, '','sa', $logs, true  );
				kyc_customize_logs_function('sa', strtoupper($type), $getKycData,$logs);

				$kycUserData = get_user_by('email', $getKycData->email);
				if( $kycUserData ){
					update_user_meta( $kycUserData->ID, 'withdrawal_suspension_5_minute', 'enable' );
					$logs = sprintf( __('Withdrawal suspension for a minutes after login enabled on kyc/kyb approval of %s at %s', CIP_TXTDOMAIN), $getKycData->email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( $kycUserData->ID, 'profile', '','member', $logs, true );
				}
				$noticeMsg = __('Your '.$type_txt.' is approved.', CIP_TXTDOMAIN);
				$noticeData = array(
					"email"		=>	$getKycData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );
				$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 = __($type_txt.' status changed', CIP_TXTDOMAIN);
				$message = sprintf( __('<h2>Dear Member,</h2><h3>Your '.$type_txt.' has been approved.</h3><p>You can check the status of your '.$type_txt.' 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>', CIP_TXTDOMAIN), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
				$htmlContent = kycMailTemplateHtmlRender( $message );
				if( get_email_send_toggle('kyc_status_change') == 1 ){
					wp_mail( $getKycData->email, $subject, $htmlContent );
				}
				$out = array( "error" => 0,'msg' => __($type_txt . ' Approved.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Something went wrong. '.$type_txt.' not approved.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_reject_kyc_verification_act', 'reject_kyc_verification_act_callback' );
function reject_kyc_verification_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPRejectionKycCIPXy_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_POST['_microid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_kyc_CIP') ), '', $decrypted_id_raw);
		// $getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` = 'pending' OR `status` = 'reject' )");
		$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
		$type = "kyc";
		$type_txt = __("KYC", CIP_TXTDOMAIN);
		if( $getKycData ){

			if( $getKycData->account_type == 'business' ){
				$type = "kyb";
				$type_txt = __("KYB", CIP_TXTDOMAIN);
			}
			$userData = get_user_by('email', $getKycData->email);
			$whereData = array( 'email' => $getKycData->email );
			$user_id = get_current_user_id();
			if( !empty( $getKycData->reject_steps ) ){
				$reject_steps = explode( ",", $getKycData->reject_steps );
			}
			$reject_steps[] = $_POST['thisStep'];
			$reject_steps = array_unique( $reject_steps );
			if( !empty( $getKycData->approve_steps ) ){
				$approve_steps = explode( ",", $getKycData->approve_steps );
				if( is_array( $approve_steps ) ){
					foreach( $approve_steps as $key => $approve_step ){
						if( in_array( $approve_step, $reject_steps ) ){
							unset( $approve_steps[ $key ] );
						}
					}
				}
			}else{
				$approve_steps = array();
			}
			$updateData = array(
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'0',
				// 'status'		=>	$getKycData->status,
				'status'		=>	'reject',
				'reject_steps'	=>	implode( ",", $reject_steps ),
				'approve_steps'	=>	implode( ",", $approve_steps ),
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				$stepName = getKycStepsName( $_POST['thisStep'] );
				if( $type == 'kyb' ){
					$stepName = getKybStepsName( $_POST['thisStep'] );
				}
				$userData = wp_get_current_user();
				$logs = sprintf( __('%s reject for %s by SA(%s) at %s. Step: %s. Reason: %s', CIP_TXTDOMAIN), $type_txt, $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A'), $stepName, $_POST['rejection_reason'] );
				// create_cip_logs_entery( 0, $type, '','sa', $logs, true  );
				kyc_customize_logs_function('sa', strtoupper($type), $getKycData,$logs,false,$stepName);
				$noticeMsg = sprintf( __('Your %s is rejected. Step: %s. Reason: %s.<br/><a href="%s">View your %s</a>', CIP_TXTDOMAIN), $type_txt, $stepName, $_POST['rejection_reason'], getKycPageLink(), $type_txt );
				$noticeData = array(
					"email"		=>	$getKycData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData );

				/* $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 = __('KYC status changed', CIP_TXTDOMAIN);
				$message = sprintf( __('<h2>Dear Member,</h2><h3>Your KYC has been rejected.</h3><p>%s</p><p>Reason: %s</p><p>You can check the status of 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>', CIP_TXTDOMAIN), $stepName, $_POST['rejection_reason'], getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
				$htmlContent = kycMailTemplateHtmlRender( $message );
				wp_mail( $getKycData->email, $subject, $htmlContent ); */
				$checkStepCount = 0;
				$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
				if( $getKycData ){
					$userData = get_user_by('email', $getKycData->email);
					$approvedCount = 0;
					$rejectedCount = 0;
					if( !empty( $getKycData->reject_steps ) ){
						$reject_steps = explode( ",", $getKycData->reject_steps );
						$rejectedCount = count( $reject_steps );
					}
					if( !empty( $getKycData->approve_steps ) ){
						$approve_steps = explode( ",", $getKycData->approve_steps );
						$approvedCount = count( $approve_steps );
					}
					$checkStepCount = $approvedCount + $rejectedCount;
				}
				/* $getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
				if( $getKycData ){
					$userData = get_user_by('email', $getKycData->email);
					if( !empty( $getKycData->reject_steps ) ){
						$reject_steps = explode( ",", $getKycData->reject_steps );
						if( in_array( 1, $reject_steps ) && in_array( 2, $reject_steps ) && in_array( 3, $reject_steps ) ){

							$updateData = array(
								'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
								'current_step'	=>	'0',
								'status'		=>	'reject',
							);
							$update = $wpdb->update( $tableKyc, $updateData, $whereData );
							if( $update ){
								$userData = wp_get_current_user();
								//log
								$logs = sprintf( __('KYC rejected for %s by SA(%s) at %s.', CIP_TXTDOMAIN), $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'kyc', '','sa', $logs, true );

								//notice
								$noticeMsg = __('Your KYC is rejected.', CIP_TXTDOMAIN);
								$noticeData = array(
									"email"		=>	$getKycData->email,
									"username"	=>	'',
									"notice"	=>	$noticeMsg,
									"status"	=>	1,
									"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
								);
								$wpdb->insert( $tableCipNotice, $noticeData );

								$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 = __('KYC status changed', CIP_TXTDOMAIN);
								$message = sprintf( __('<h2>Dear Member,</h2><h3>Your KYC has been rejected.</h3><p>You can check the status of 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>', CIP_TXTDOMAIN), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
								$htmlContent = kycMailTemplateHtmlRender( $message );
								wp_mail( $getKycData->email, $subject, $htmlContent );

							}
						}
					}
				} */

				$out = array( "error" => 0,'msg' => sprintf( __('%s %s is rejected',CIP_TXTDOMAIN), $type_txt, $stepName ), 'checkStepCount' => $checkStepCount, 'type' => $type );
				$out['tabMove'] = $_POST['thisStep'] + 1;

			}else{
				$out = array( "error" => 1,'msg' => __('Something went wrong. '.$type_txt.' not reject.',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_approvedStepKycact', 'approvedStepKycact_callback' );
function approvedStepKycact_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN), 'isFullyApprove' => 0, 'tabMove' => 1 ,'checkStepCount' => 0 ,'type' => 'kyc' );
	if( wp_verify_nonce( $_POST['_micro'],'_YxCIPApproveStepKycCIPXy_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableKyc = $wpdb->prefix.'kyc_data';
		$tableCipNotice = $wpdb->prefix.'cip_notice';
		$decrypted_id_raw = base64_decode( $_POST['_microid'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_kyc_CIP') ), '', $decrypted_id_raw);
		$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
		$type = "kyc";
		$type_txt = __("KYC", CIP_TXTDOMAIN);
		if( $getKycData ){
			if( $getKycData->account_type == 'business' ){
				$type = "kyb";
				$type_txt = __("KYB", CIP_TXTDOMAIN);
			}
			$userData = get_user_by('email', $getKycData->email);
			$whereData = array( 'email' => $getKycData->email );
			$user_id = get_current_user_id();
			if( !empty( $getKycData->approve_steps ) ){
				$approve_steps = explode( ",", $getKycData->approve_steps );
			}
			$approve_steps[] = $_POST['thisStep'];
			$approve_steps = array_unique( $approve_steps );

			if( !empty( $getKycData->reject_steps ) ){
				$reject_steps = explode( ",", $getKycData->reject_steps );
				if( is_array( $reject_steps ) ){
					foreach( $reject_steps as $key => $reject_step ){
						if( in_array( $reject_step, $approve_steps ) ){
							unset( $reject_steps[ $key ] );
						}
					}
				}
			}else{
				$reject_steps = array();
			}
			$updateData = array(
				'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
				'current_step'	=>	'0',
				'status'		=>	$getKycData->status,
				'reject_steps'	=>	implode( ",", $reject_steps ),
				'approve_steps'	=>	implode( ",", $approve_steps ),
			);
			$update = $wpdb->update( $tableKyc, $updateData, $whereData );
			if( $update ){
				if( $type == 'kyb' ){
					$stepName = getKybStepsName( $_POST['thisStep'] );
				}else{
					$stepName = getKycStepsName( $_POST['thisStep'] );
				}
				$userData = wp_get_current_user();
				$logs = sprintf( __($type_txt . ' step %s is approved for %s by SA(%s) at %s.', CIP_TXTDOMAIN), $stepName, $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
				// create_cip_logs_entery( 0, $type, '','sa', $logs, true  );
				kyc_customize_logs_function('sa', strtoupper($type), $getKycData,$logs,false,$stepName);
				/* $noticeMsg = sprintf( __('Your KYC step <b>%s</b> is approved. <br/><a href="%s">View your KYC</a>', CIP_TXTDOMAIN), $stepName, getKycPageLink() );
				$noticeData = array(
					"email"		=>	$getKycData->email,
					"username"	=>	'',
					"notice"	=>	$noticeMsg,
					"status"	=>	1,
					"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$wpdb->insert( $tableCipNotice, $noticeData ); */

				/* $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 = __('KYC status changed', CIP_TXTDOMAIN);
				$message = sprintf( __('<h2>Dear Member,</h2><h3>Your KYC has been rejected.</h3><p>%s</p><p>Reason: %s</p><p>You can check the status of your KYC via this link: <a href="%s">%s</a></p>', CIP_TXTDOMAIN), $stepName, $_POST['rejection_reason'], getKycPageLink(), getKycPageLink() );
				$htmlContent = kycMailTemplateHtmlRender( $message );
				wp_mail( $getKycData->email, $subject, $htmlContent ); */
				$out = array( "error" => 0,'msg' => sprintf( __( $type_txt . ' %s is approved',CIP_TXTDOMAIN), $stepName ), 'isFullyApprove' => 0 ,'checkStepCount' => 0, 'type' => $type );
				$out['tabMove'] = $_POST['thisStep'] + 1;
				$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $id AND ( `status` <> '' AND `status` IS NOT NULL )");
				if( $getKycData ){
					$userData = get_user_by('email', $getKycData->email);
					$approvedCount = 0;
					$rejectedCount = 0;
					if( !empty( $getKycData->reject_steps ) ){
						$reject_steps = explode( ",", $getKycData->reject_steps );
						$rejectedCount = count( $reject_steps );
					}
					if( !empty( $getKycData->approve_steps ) ){
						$approve_steps = explode( ",", $getKycData->approve_steps );
						$approvedCount = count( $approve_steps );
						/* if( in_array( 1, $approve_steps ) && in_array( 2, $approve_steps ) && in_array( 3, $approve_steps ) ){

							$updateData = array(
								'lastupdate'	=>	date_i18n( 'Y-m-d H:i:s' ),
								'current_step'	=>	'0',
								'status'		=>	'approved',
							);
							$update = $wpdb->update( $tableKyc, $updateData, $whereData );
							if( $update ){
								$userData = wp_get_current_user();
								//log
								$logs = sprintf( __('KYC approved for %s by SA(%s) at %s.', CIP_TXTDOMAIN), $getKycData->email, $userData->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'kyc', '','sa', $logs, true  );

								//notice
								$noticeMsg = __('Your KYC is approved.', CIP_TXTDOMAIN);
								$noticeData = array(
									"email"		=>	$getKycData->email,
									"username"	=>	'',
									"notice"	=>	$noticeMsg,
									"status"	=>	1,
									"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
								);
								$wpdb->insert( $tableCipNotice, $noticeData );

								$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 = __('KYC status changed', CIP_TXTDOMAIN);
								$message = sprintf( __('<h2>Dear Member,</h2><h3>Your KYC has been approved.</h3><p>You can check the status of 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>', CIP_TXTDOMAIN), getKycPageLink(), getKycPageLink(), $siteUrl, $siteUrlName );
								$htmlContent = kycMailTemplateHtmlRender( $message );
								wp_mail( $getKycData->email, $subject, $htmlContent );
								$out['isFullyApprove'] = 1;

							}
						} */
					}
					$out['checkStepCount'] = $approvedCount + $rejectedCount;
				}

			}else{
				$out = array( "error" => 1,'msg' => __('Something went wrong. '.$type_txt.' not approved.',CIP_TXTDOMAIN), 'isFullyApprove' => 0 );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function getKycStepsName( $stepId = 0 ){
	$stepName = "";
	switch ($stepId) {
		case '1':
			$stepName = __('Personal Information', CIP_TXTDOMAIN);
			break;
		/* case '2':
			$stepName = __('Registered Address', CIP_TXTDOMAIN);
			break; */
		case '2':
			$stepName = __('Identification Document', CIP_TXTDOMAIN);
			break;
		case '3':
			$stepName = __('Proof of Address', CIP_TXTDOMAIN);
			break;

		case '4':
			$stepName = __('Confirmation', CIP_TXTDOMAIN);
			break;

		default:
			$stepName = "";
			break;
	}
	return $stepName;
}
function getKybStepsName( $stepId = 0 ){
	$stepName = "";
	switch ($stepId) {
		case '1':
			$stepName = __('Business Details', CIP_TXTDOMAIN);
			break;
		case '2':
			$stepName = __('Contact Details', CIP_TXTDOMAIN);
			break;
		case '3':
			$stepName = __('Director or Equivalent Person', CIP_TXTDOMAIN);
			break;

		case '4':
			$stepName = __('Upload Documents', CIP_TXTDOMAIN);
			break;

		case '5':
			$stepName = __('Confirmation', CIP_TXTDOMAIN);
			break;

		default:
			$stepName = "";
			break;
	}
	return $stepName;
}
function kycMailTemplateHtmlRender( $message ){

	$htmlurl = CIP_PLUGIN_FOLDER.'mail_template_kyc.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;
}
function getKycPageLink(){
	return get_the_permalink( get_page_by_path('content/operations/member/my-kyc') );
}
add_action( 'init', 'prohibit_access_to_admin' );
function prohibit_access_to_admin() {
	if ( (defined('DOING_AJAX') && DOING_AJAX) || ( strpos($_SERVER['SCRIPT_NAME'], 'admin-post.php') ) ) {
        return;
    }
	if ( is_admin() && !current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
		wp_redirect( home_url() ); exit;
	}
}
add_action('template_redirect', 'cip_check_wpadmin_login_authentication');
function cip_check_wpadmin_login_authentication(){
	if( is_user_logged_in() ){
		if( !isset( $_SESSION['refAccount'] ) || empty( $_SESSION['refAccount'] ) ){
			$user = wp_get_current_user();
			$_SESSION['refAccount']	= $user->user_email;
			// $logs = sprintf( __('%s logged-out ( at email session check ) %s', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
			$logs = sprintf( __('%s session restore ( at email session check ) %s', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $user->ID, 'session_restore', '','member', $logs, true );
			// wp_logout();
			wp_redirect( site_url() );
			exit;
		}
	}
}
/* add_action( 'wp_authenticate' , 'cip_check_wpadmin_login_authentication' );
function cip_check_wpadmin_login_authentication( $username ){
	$user = new WP_User($username);
	$user_role_member=$user->roles[0];
	if(!in_array($user_role_member,array('administrator'))){
	// if( !$user->has_cap( 'administrator' ) ){
		session_destroy();
		wp_logout();
		wp_redirect( home_url() );
		exit;
	}
} */
add_action( 'wp_ajax_view_attachments_lsh_act', 'view_attachments_lsh_act_callback' );
function view_attachments_lsh_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableLSHPending = $wpdb->prefix.'csr_lsh_pending';
		$decrypted_id_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPSecurityHold') ), '', $decrypted_id_raw);
		$column = "";
		if( $_POST['type'] == 'type1' ){
			$column = 'member_passport';
		}else if( $_POST['type'] == 'type2' ){
			$column = 'piece_paper_wallet_address';
		}
		$getPendingList = $wpdb->get_row("SELECT `$column` FROM $tableLSHPending WHERE 1 AND `id`=$id");
		if( $getPendingList ){
			$out = array( "error" => 0,'msg' => __('Success', CIP_TXTDOMAIN), 'src' => 'data:image/jpg;charset=utf8;base64,'.base64_encode( $getPendingList->$column ) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_view_attachments_adrs_act', 'view_attachments_adrs_act_callback' );
function view_attachments_adrs_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableAddressPending = $wpdb->prefix.'csr_address_pending';
		$decrypted_id_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIPpassportCIP') ), '', $decrypted_id_raw);
		$column = "";
		if( $_POST['type'] == 'type1' ){
			$column = 'member_passport';
		}else if( $_POST['type'] == 'type2' ){
			$column = 'piece_paper_wallet_address';
		}
		$getPendingAddress = $wpdb->get_row("SELECT `$column` FROM $tableAddressPending WHERE 1 AND `id`=$id");
		if( $getPendingAddress ){
			$out = array( "error" => 0,'msg' => __('Success', CIP_TXTDOMAIN), 'src' => 'data:image/jpg;charset=utf8;base64,'.base64_encode( $getPendingAddress->$column ) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/* add_action('wp_ajax_test_update_username_script', 'test_update_username_script');
function test_update_username_script(){
	global $wpdb;
	$tableName = $wpdb->prefix.'csr_address_pending';
	$tableToken = $wpdb->prefix.'token_holder';
	$getLists = $wpdb->get_results("SELECT * FROM $tableName WHERE 1");
	foreach( $getLists as $getList ){
		$username = "";
		$getWalletRecord = $wpdb->get_row("SELECT `id`,`eth_address`,`email`,`username` FROM $tableToken WHERE 1 AND email = '".$getList->email."'");
		if( $getWalletRecord ){
			$username = $getWalletRecord->username;
			$update = $wpdb->update( $tableName, array( 'username' => $username ), array( 'id' => $getList->id ) );
		}
	}
	exit;
} */
//5747 card
add_action( 'wp_ajax_cip_actionEnableCountries_act', 'cip_actionEnableCountries_act_callback' );
function cip_actionEnableCountries_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyEnableCountriesyX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$cipDisabledCountries = get_option( 'cipDisabledCountries' );
		$cipDisabledCountries = maybe_unserialize( $cipDisabledCountries );
		if( isset( $_POST['thisCountry'] ) && $_POST['thisCountry'] != "" && is_array( $cipDisabledCountries ) && $_POST['isEnabling'] == 1 ){
			foreach( $cipDisabledCountries as $key => $cipDisabledCountry ){
				if( sanitize_title( $_POST['thisCountry'] ) == sanitize_title( $cipDisabledCountry ) ){
					unset( $cipDisabledCountries[$key] );
					$userData = wp_get_current_user();
					$logs = sprintf( __('%s country enabled by %s at %s', CIP_TXTDOMAIN), wp_unslash( $_POST['thisCountry'] ), $userData->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( $userData->ID, 'country', '','sm', $logs, true  );
				}
			}
			update_option( 'cipDisabledCountries', maybe_serialize( $cipDisabledCountries ) );
			$out = array( "error" => 0,'msg' => __('Enabled', CIP_TXTDOMAIN), 'label' => 'Enabled' );
		}else if( isset( $_POST['thisCountry'] ) && $_POST['thisCountry'] != "" && is_array( $cipDisabledCountries ) ){
			$cipDisabledCountries[] = wp_unslash( $_POST['thisCountry'] );
			$userData = wp_get_current_user();
			$logs = sprintf( __('%s country disabled by %s at %s', CIP_TXTDOMAIN), wp_unslash( $_POST['thisCountry'] ), $userData->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $userData->ID, 'country', '','sm', $logs, true  );
			$cipDisabledCountries = array_unique( $cipDisabledCountries );
			sort( $cipDisabledCountries );
			update_option( 'cipDisabledCountries', maybe_serialize( $cipDisabledCountries ) );
			$out = array( "error" => 0,'msg' => __('Disabled', CIP_TXTDOMAIN), 'label' => 'Disabled' );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_addCountrytoDisableAct', 'addCountrytoDisableAct_callback' );
function addCountrytoDisableAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyaddCountrytoDisableyX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$cipDisabledCountries = get_option( 'cipDisabledCountries' );
		$cipDisabledCountries = maybe_unserialize( $cipDisabledCountries );
		if( isset( $_POST['country'] ) && $_POST['country'] != "" && is_array( $cipDisabledCountries ) ){
			$cipDisabledCountries[] = wp_unslash( $_POST['country'] );
			$userData = wp_get_current_user();
			$logs = sprintf( __('%s country disabled by %s at %s', CIP_TXTDOMAIN), wp_unslash( $_POST['country'] ), $userData->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $userData->ID, 'country', '','sm', $logs, true  );
			$cipDisabledCountries = array_unique( $cipDisabledCountries );
			sort( $cipDisabledCountries );
			update_option( 'cipDisabledCountries', maybe_serialize( $cipDisabledCountries ) );
			$out = array( "error" => 0,'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $cipDisabledCountries );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csr_withdrawal_setting_act', 'csr_withdrawal_setting_act_callback' );
function csr_withdrawal_setting_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CsrWithdrawalSettingsrsC_' ) && current_user_can( 'supportagent' ) ){
		$userData = wp_get_current_user();
			
		$old_minimum_withdrawal_amount = ( !empty( get_option('minimum_withdrawal_amount') ) ) ? get_option('minimum_withdrawal_amount') : '' ;
		$old_withdrawal_fee = ( !empty( get_option('withdrawal_fee') ) ) ? get_option('withdrawal_fee') : '' ;
		$old_withdrawal_fee_csr25 = ( !empty( get_option('withdrawal_fee_csr25') ) ) ? get_option('withdrawal_fee_csr25') : '' ;
		$old_csr_fee_useremail = ( !empty( get_option('csr_fee_useremail') ) ) ? get_option('csr_fee_useremail') : '' ;
		$old_withdrawal_review_limit = ( !empty( get_option('withdrawal_review_limit') ) ) ? get_option('withdrawal_review_limit') : '' ;
		
		$new_minimum_withdrawal_amount = $_POST['minimum_withdrawal_amount'];
		$new_withdrawal_fee = $_POST['withdrawal_fee'];
		$new_withdrawal_fee_csr25 = $_POST['withdrawal_fee_csr25'];
		$new_csr_fee_useremail = $_POST['csr_fee_useremail'];
		$new_withdrawal_review_limit = $_POST['withdrawal_review_limit'];

		update_option( 'minimum_withdrawal_amount', $new_minimum_withdrawal_amount );
		update_option( 'withdrawal_fee', $new_withdrawal_fee );
		update_option( 'withdrawal_fee_csr25', $new_withdrawal_fee_csr25 );
		update_option( 'csr_fee_useremail', $new_csr_fee_useremail );
		update_option( 'withdrawal_review_limit', $new_withdrawal_review_limit );

		$logs = sprintf( __('csr withdrawal setting update by %s at %s old value minimum_withdrawal_amount=%s, withdrawal_fee=%s, withdrawal_fee_csr25=%s, fee email=%s, withdrawal_review_limit=%s new value minimum_withdrawal_amount=%s, withdrawal_fee=%s, withdrawal_fee_csr25=%s, new fee email=%s, new withdrawal_review_limit=%s', CIP_TXTDOMAIN), $userData->user_email, date_i18n('d/m/Y H:i A'), $old_minimum_withdrawal_amount, $old_withdrawal_fee,$old_withdrawal_fee_csr25, $old_csr_fee_useremail, $old_withdrawal_review_limit, $new_minimum_withdrawal_amount, $new_withdrawal_fee,$new_withdrawal_fee_csr25, $new_csr_fee_useremail, $new_withdrawal_review_limit );
		create_cip_logs_entery( $userData->ID, 'setting', '','sa', $logs, true  );
		$out = array( "error" => 0,'msg' => __('Updated', CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csrwithdrawalaction', 'csrwithdrawalaction_callback' );
function csrwithdrawalaction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	if (empty($client_ip_address = corsairlogin_client_ip())) {
		echo wp_json_encode( $out );
		exit;
	}

	if( wp_verify_nonce( $_POST['_micro'],'_XyCIPWithdrawalCSRPICyX_' ) && current_user_can( 'member' ) ){
		global $wpdb;
		$token = $_POST['token'];
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;

		$clientWithdrawalRequestKey = 'user_withdrawal_request_attempt_' . $user_id;

		$isWithdrawalSuspend = get_user_meta( $user_id, 'csrnow_withdrawal_suspend', true );
		if( $isWithdrawalSuspend == '1' ){
			$out = array( "error" => 1,'msg' => __('Withdrawals are presently suspended on this account. Please contact support.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$withdrawal_suspension = get_user_meta( $user_id, 'withdrawal_suspension_5_minute', true );
		if( $withdrawal_suspension == 'enable' ){
			if( !empty( $_SESSION['logged_time'] ) && $_SESSION['logged_time'] >= time() ){
				$out = array( "error" => 1,'msg' => __('Withdrawal suspension, after timer reset you can withdraw.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}

		$minimum_withdrawal_amount = ( !empty( get_option('minimum_withdrawal_amount') ) ) ? get_option('minimum_withdrawal_amount') : 0 ;
		$withdrawal_fee = ( !empty( get_option('withdrawal_fee') ) ) ? get_option('withdrawal_fee') : 0 ;
		$withdrawal_fee_csr25 = ( !empty( get_option('withdrawal_fee_csr25') ) ) ? get_option('withdrawal_fee_csr25') : 0 ;

		if( strtoupper( $token ) == 'CSR25' ){
			$withdrawal_fee = $withdrawal_fee_csr25; 
		}
		if (empty($client_ip_address = corsairlogin_client_ip())) {
			echo wp_json_encode( $out );
			exit;
		}
		$clientResendKey = 'resend_attempt_withdraw' . $client_ip_address;

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

		$eth_address = trim( $_POST['csr_wallet_address'] );
		$tableWithdrawalBlockAddress = $wpdb->prefix.'withdrawal_block_address';
		$checkIsBlockAddress = $wpdb->get_row("SELECT * FROM $tableWithdrawalBlockAddress WHERE 1 AND LCASE(`withdrawal_block_address`)='". strtolower( $eth_address ) ."'");
		if( $checkIsBlockAddress ){
			$out = array( "error" => 1,'msg' => sprintf( __('Withdrawal to this address is not possible as this address is of %s. Please select another address.',CIP_TXTDOMAIN), $checkIsBlockAddress->address_name ), 'isAddressError' => 1 );
			echo wp_json_encode( $out );
			exit;
		}
		$restricted_csr_address = array(
			strtolower( '0x75Ecb52e403C617679FBd3e77A50f9d10A842387' ),
			strtolower( '0x4e59d2f5e7b2958771abd87d72be86d4d9c4493b' ),
			strtolower( '0x53849b536b2f12a745a63f417e7cb366d0ab1151' ),
			strtolower( '0xf95e621a37303e4e940fff7902212bdaa9ddfe9a' ),
			strtolower( '0x47a55a19f6e31eaec335086966cd52c2869fe690' ),
			strtolower( '0xa8a1329655e63df79d6a338f88cc0f56c127ede2' ),
		);
		if( in_array( strtolower( $eth_address ), $restricted_csr_address ) ){
			$out = array( "error" => 1,'msg' => __('CSR wallet address is invalid',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( $_POST['step'] == 1 ){
			if( !empty( $eth_address ) && AddressValidator::isValid( $eth_address ) !== AddressValidator::ADDRESS_VALID ){
				$out = array( "error" => 1,'msg' => __('CSR wallet address is invalid',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
			// $csr_balance = get_user_csr_balance( $user_id );
			$csr_balance = get_user_csr_balance( $refAccount,'', $token );
			if( $_POST['csr_withdrawal_amount'] > $csr_balance ){
				$out = array( "error" => 1,'msg' =>sprintf( __('The requested withdrawal amount exceeds available %s Balance', CIP_TXTDOMAIN), $token ) );
				echo wp_json_encode( $out );
				exit;
			}
			if( $_POST['csr_withdrawal_amount'] < $minimum_withdrawal_amount ){
				$out = array( "error" => 1,'msg' => sprintf( __('Minimum withdrawal amount is %s %s', CIP_TXTDOMAIN), number_format( $minimum_withdrawal_amount, 2 ), $token ) );
				echo wp_json_encode( $out );
				exit;
			}
			$received_amount = $_POST['csr_withdrawal_amount'] - $withdrawal_fee;

			$data = array(
				'eth_address'		=>	$_POST['csr_wallet_address'],
				'withdraw_amount'	=>	number_format( $_POST['csr_withdrawal_amount'], 2 ) .' '. $token,
				'withdrawal_fee'	=>	number_format( $withdrawal_fee, 2 ) .' '. $token,
				'received_amount'	=>	number_format( $received_amount, 2 ) .' '. $token,
			);
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'data' => $data );
		}else if( $_POST['step'] == 2 ){
			if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
				if ((get_transient($clientResendKey) !== false)) {
					$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
			$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			$google_auth_key_withdrawal = get_user_meta( $user_id, 'google_auth_key_withdrawal', true );
			$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_withdrawal == 1 ) ? 1 : 0;

			if( $corsair_2fa_ga != 'yes' || $ga2fa_login_enabled != 1 ){
				$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$otpContent = "";
			$otpGAContent = "";
			$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_withdrawal', $user_otp );
			update_user_meta( $user_id, 'user_otp_withdrawal_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',CIP_TXTDOMAIN), get_option('blogname') ); } );
			add_filter( 'wp_mail_content_type', function(){ return "text/html"; } );
			$subject = sprintf(__("%s - Email OTP Verification for Withdrawal", 'corsair-login'), $blogname);
			$ip_location_details = "";
			$geopluginURL='http://www.geoplugin.net/php.gp?ip='.cip_get_client_ip();
			$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
			$city = $addrDetailsArr['geoplugin_city'];
			$country = $addrDetailsArr['geoplugin_countryName'];
			if( !empty( $city ) || !empty( $country ) ){
				$ip_location_details = $city .', '. $country;
			}
			$message = __('<h2>Confirm Your '. $token .' Withdrawal</h2>', CIP_TXTDOMAIN );
			$message .= sprintf( __('<p>You\'ve initiated a request to withdraw %s %s to the following address:</p><p><b>Address: %s</b></p>', CIP_TXTDOMAIN ), number_format( $_POST['csr_withdrawal_amount'], 2, '.', '' ), $token, $eth_address );
			$message .= __('<p style="color:red;">Please carefully review the withdrawal address before you proceed. We will not be responsible for any funds sent to the wrong address.</p>', CIP_TXTDOMAIN );
			$message .= sprintf( __('<p>IP Location: %s<br/>IP: %s</p>', CIP_TXTDOMAIN ), $ip_location_details, cip_get_client_ip() );
			$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
			$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
			$message .= __('<p><b>Security note</b></p>', CIP_TXTDOMAIN );
			$message .= __('<ul style="list-style-type: disc;"><li>Beware of unsolicited emails requesting personal information or urgent actions.</li><li>Be aware of phising and other ilegitimate websites and always make sure you are visiting the official CSRnow.com website when entering any sensitive data.</li><li>Stay vigilant against deceptive emails, especially if they contain misspellings or odd formatting.</li></ul>', CIP_TXTDOMAIN);
			$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
			$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
			/* $message .= sprintf(__('<h2>You are attempting to withdraw in %s</h2><p>Here is your OTP (One-Time-Passcode) to withdraw.</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>', CIP_TXTDOMAIN ), $siteUrlName, $user_otp, $siteUrl, $siteUrlName ); */
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
				set_transient($clientResendKey, '1', 60);
				ob_start();
				?>
				<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
				<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 mb-1" 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>
				<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_withdraw" 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_withdraw').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_withdraw').text("Resend in "+(sec)+' s')
								}else{
									$('#resend_withdraw').attr('data-stat','').removeClass('disabled').text('Resend OTP')
									clearInterval(countdown)
								}
							}, 1000);
						}
					});
				</script>
				<?php
				$otpContent = ob_get_clean();
				ob_start();
				?>
				<hr class="mt-4 mb-3">
				<div class="otp_section pb-3">
					<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
					<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
					<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
				</div>
				<?php
				$otpGAContent = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'otpContent' => $otpContent, 'otpGAContent' => $otpGAContent );
			}
		}else if( $_POST['step'] == 3 ){

			$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
			if( $decryptedUserId == $user_id ){
				$user_otp = get_user_meta( $user_id, 'user_otp_withdrawal', true );
				$user_otp_expiration = get_user_meta( $user_id, 'user_otp_withdrawal_expiration', true );
				$emailOTPValid = false;
				$gaOTPValid = false;
				if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
					$emailOTPValid = true;
				}
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				if( !empty( $_POST['user_ga_otp'] ) ){
					$google2fa = new \PragmaRX\Google2FA\Google2FA();
					if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
						$gaOTPValid = true;
					}
				}
				if( $emailOTPValid === false ){
					$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				if( $gaOTPValid === false ){
					$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
				$username = "";
				$first_name = "";
				$last_name = "";
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$getUsername = $wpdb->get_row("SELECT `first_name`,`last_name`,`username` FROM $tableTokenHolder WHERE `email`='".$current_user->user_email."' ORDER BY `id` DESC");
				if( $getUsername ){
					$username = $getUsername->username;
					$first_name = $getUsername->first_name;
					$last_name = $getUsername->last_name;
				}
				if( $emailOTPValid === true && $gaOTPValid === true ){
					$received_amount = $_POST['csr_withdrawal_amount'] - $withdrawal_fee;
					$withdrawal_id = uniqidReal();

					if( empty( $withdrawal_id ) ){
						$out = array( "error" => 1,'msg' => __('Error occurred during withdrawal, Please try agian', CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}

					$withdrawal_process_status = 'Pending';
					$withdrawal_review_limit = ( !empty( get_option('withdrawal_review_limit') ) ) ? get_option('withdrawal_review_limit') : 0;
					if( $_POST['csr_withdrawal_amount'] > $withdrawal_review_limit ){
						$withdrawal_process_status = 'Under review';
					}

					$data = array(
						'user_id'					=>	$user_id,
						'withdrawal_id'				=>	$withdrawal_id,
						'username'					=>	$username,
						'first_name'				=>	$first_name,
						'last_name'					=>	$last_name,
						'email'						=>	$current_user->user_email,
						'eth_address'				=>	$eth_address,
						'withdraw_amount'			=>	$_POST['csr_withdrawal_amount'],
						'min_withdraw_amount'		=>	$minimum_withdrawal_amount,
						'withdrawal_fee'			=>	$withdrawal_fee,
						'received_amount'			=>	$received_amount,
						'status'					=>	0,
						'requested_date'			=>	date_i18n('Y-m-d H:i:s'),
						'amount_to_distribute'		=>	$received_amount,
						'withdrawal_process_status'	=>	$withdrawal_process_status,
						'token' 					=>  $token
					);
					$star_request_url = add_query_arg( 'email', urlencode( $current_user->user_email ), 'https://amplivo.com/api/userstatus/get' );
					$star_response = wp_remote_get( $star_request_url );
					if( !is_wp_error( $star_response ) ) {
						$star_response_body = wp_remote_retrieve_body( $star_response );
						$star_data = json_decode( $star_response_body );
						if(isset( $star_data->Star_1 )){
							$user_star = 1;
						}
						if(isset( $star_data->Star_2 )){
							$user_star = 2;
						}
						if(isset( $star_data->Star_3 )){
							$user_star = 3;
						}
						if(isset( $star_data->Star_4 )){
							$user_star = 4;
						}
						if(isset( $star_data->Star_5 )){
							$user_star = 5;
						}
						if(isset( $star_data->Star_6 )){
							$user_star = 6;
						}
						if(isset( $star_data->Star_7 )){
							$user_star = 7;
						}
						if(isset( $user_star)){
							$data['user_star'] = $user_star;
						}
					}

					if ((get_transient($clientWithdrawalRequestKey) !== false)) {
						$out = array( "error" => 1,'msg' => __('Slow down a bit', CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}

					$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
					$csr_balance = get_user_csr_balance( $refAccount,'', $token );
					if( $_POST['csr_withdrawal_amount'] > $csr_balance ){
						$out = array( "error" => 1,'msg' =>sprintf( __('The requested withdrawal amount exceeds available %s Balance', CIP_TXTDOMAIN), $token ) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $_POST['csr_withdrawal_amount'] < $minimum_withdrawal_amount ){
						$out = array( "error" => 1,'msg' => sprintf( __('Minimum withdrawal amount is %s %s', CIP_TXTDOMAIN), number_format( $minimum_withdrawal_amount, 2 ), $token ) );
						echo wp_json_encode( $out );
						exit;
					}

					$insert = $wpdb->insert( $tableWithdraw, $data );
					if( $insert ){

						set_transient($clientWithdrawalRequestKey, '1', 10);

						$lastid = $wpdb->insert_id;
						/* $withdrawal_id = $lastid + 1000;
						$updateRow = $wpdb->update( $tableWithdraw, ['withdrawal_id' => $withdrawal_id] , ['id' => $lastid] ); */
						$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 = __('Request for a withdrawal', CIP_TXTDOMAIN);

						//notice of withdrawal request
						$tableCipNotice = $wpdb->prefix.'cip_notice';
						$notificationMessageText = sprintf( __('Your withdrawal request for %s %s is now being reviewed and processed.', CIP_TXTDOMAIN), number_format( $_POST['csr_withdrawal_amount'], 2 ), $token );
						$noticeData = array(
							"email"		=>	$current_user->user_email,
							"username"	=>	'',
							"notice"	=>	$notificationMessageText,
							"status"	=>	1,
							"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' )
						);
						$wpdb->insert( $tableCipNotice, $noticeData );
						
						$messageText = sprintf(
							__('<p class="text-left text-size-18">Your withdrawal request for %s %s is now being reviewed and processed.</p><p class="text-left text-size-18">You will receive %s %s at blockchain address %s.</p><p class="text-left text-size-18">Withdrawal fees %s %s.</p><p class="text-left text-size-18"><b>Transaction ID: %s</b></p>', CIP_TXTDOMAIN),
							number_format( $_POST['csr_withdrawal_amount'], 2 ),
							$token,
							number_format( $received_amount, 2 ),
							$token,
							$eth_address,
							number_format( $withdrawal_fee, 2 ),
							$token,
							$withdrawal_id
						);

						$message = sprintf( __('<h2>Dear Member,</h2><h3>%s', CIP_TXTDOMAIN), $messageText );
						$htmlContent = mailTemplateHtmlRender( $message );
						if( get_email_send_toggle('withdrawal_request') == 1 ){
							wp_mail( $current_user->user_email, $subject, $htmlContent );
						}
						$out = array( "error" => 0,'msg' => $messageText);
						$logs = sprintf( __('Request for a withdrawal of %s %s to Blockchain address %s, Withdrawal fee %s %s, Withdrawal-ID: %s by %s at %s', CIP_TXTDOMAIN), number_format( $_POST['csr_withdrawal_amount'], 2 ), $token, $eth_address, number_format( $withdrawal_fee, 2 ), $token, $withdrawal_id, $current_user->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( $current_user->ID, 'withdraw', '','member', $logs, true );

						$logsFees = sprintf( __('Fees received from %s, Fee: %s %s at %s', CIP_TXTDOMAIN), $current_user->user_email, number_format( $withdrawal_fee, 2 ), $token, date_i18n('d/m/Y H:i A') );
						$transactionData = array(
							'user_id'			=>	$user_id,
							'txn_id'			=>	$withdrawal_id,
							'txn_id_ref'		=>	$withdrawal_id,
							'email'				=>	$current_user->user_email,
							'username'			=>	$username,
							'eth_address'		=>	$eth_address,
							'withdrawal_amount'	=>	$_POST['csr_withdrawal_amount'],
							'received_amount'	=>	$received_amount,
							'withdrawal_fee'	=>	$withdrawal_fee,
							'type'				=>	'withdrawal',
							'description'		=>	$logs,
							'short_description'	=>	__('CSR withdrawn to blockchain', CIP_TXTDOMAIN),
							'_date'				=>	date_i18n('Y-m-d H:i:s'),
							'status'			=>	0,
							'token' 			=> $token
						);
						$transInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );

						$csrFeeUserEmail = ( !empty( get_option('csr_fee_useremail') ) ) ? get_option('csr_fee_useremail') : 'wayne@corsairnow.com';
						$feesUserData = get_user_by('email', $csrFeeUserEmail);
						$fees_user_id = 0;
						if( $feesUserData ){
							$fees_user_id = $feesUserData->ID;
						}
						$feesTxnId = uniqidReal();
						$feesTransactionData = array(
							'user_id'			=>	$fees_user_id,
							'txn_id'			=>	$feesTxnId,
							'txn_id_ref'		=>	$withdrawal_id,
							'email'				=>	$csrFeeUserEmail,
							'username'			=>	$feesUserData->username,
							'withdrawal_amount'	=>	0,
							'received_amount'	=>	$withdrawal_fee,
							'withdrawal_fee'	=>	0,
							'type'				=>	'deposit',
							'description'		=>	$logsFees,
							'short_description'	=>	$logsFees,
							'_date'				=>	date_i18n('Y-m-d H:i:s'),
							'status'			=>	0,
							'token'				=>  $token
						);
						$feesTransInsert = $wpdb->insert( $tableTransactionHistory, $feesTransactionData );
						if( $feesTransInsert ){
							$currentBalance = get_user_csr_balance( $csrFeeUserEmail, 'total', $token );
							$logsFeesNew = sprintf( __('%s %s fee added to admin account %s at %s Current balance %s %s', CIP_TXTDOMAIN), number_format( $withdrawal_fee ), $token, $csrFeeUserEmail,  date_i18n('d/m/Y H:i A'), number_format( $currentBalance ), $token );
							create_cip_logs_entery( $fees_user_id, 'wallet_delivery', '','sm', $logsFeesNew, true  );
							create_cip_logs_entery( $fees_user_id, 'wallet_delivery', '','sm', $logsFees, true  );
						}
					}
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function uniqidReal($lenght = 16) {
    if (function_exists("random_bytes")) {
        $bytes = random_bytes(ceil($lenght / 2));
    } elseif (function_exists("openssl_random_pseudo_bytes")) {
        $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
    } else {
        return false;
    }
	$realId = strtoupper( substr(bin2hex($bytes), 0, $lenght) );
	$realId = implode("-", str_split( $realId, 4));
    return $realId;
}
add_action( 'wp_ajax_percentage_withdrawal_act', 'percentage_withdrawal_act_callback' );
function percentage_withdrawal_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'member' ) ){
		$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		$minimum_withdrawal_amount = ( !empty( get_option('minimum_withdrawal_amount') ) ) ? get_option('minimum_withdrawal_amount') : 0;
		$userData = wp_get_current_user();
		$user_id = $userData->ID;
		// $csr_amount = get_user_csr_balance( $user_id );
		$csr_amount = get_user_csr_balance( $refAccount );
		$percentageNumber = ( $csr_amount * $_POST['thisVal'] ) / 100;
		$percentage = number_format( $percentageNumber, 2, '.', '');
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'percentage' => $percentage );
	}
	echo wp_json_encode( $out );
	exit;
}
function get_user_csr_balance( $user_id = 0, $type = 'available', $tokenType = 'csr' ){
	global $wpdb;
	$tokenType = strtolower( $tokenType );
	$current_user = wp_get_current_user();
	$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
	$userData = get_user_by( 'id', $user_id );
	$final_amount = 0;

	if( !empty( $user_id ) ){
		$refAccount = $user_id;
	}else{
		$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	}

	$tokenTypeCondition = " AND `token`='". $tokenType ."'";

	if( !empty( $refAccount ) ){
		$creditData = $wpdb->get_row("SELECT COALESCE(SUM(`received_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$refAccount."' AND `type`='deposit' AND `status`=0 $tokenTypeCondition");
		if( $type == 'total' ){
			$debitData = $wpdb->get_row("SELECT COALESCE(SUM(`withdrawal_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$refAccount."' AND `type`='withdrawal' AND `status`=2 $tokenTypeCondition");
		}else{
			$debitData = $wpdb->get_row("SELECT COALESCE(SUM(`withdrawal_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$refAccount."' AND `type`='withdrawal' AND (`status`=0 OR `status`=1 OR `status`=2) $tokenTypeCondition");
		}
		try {
			$final_amount = $creditData->credit_amount - $debitData->credit_amount;
		} catch (\Throwable $th) {
			$final_amount = 0;
		}
	}
	/* if( $userData ){
		$creditData = $wpdb->get_row("SELECT COALESCE(SUM(`received_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$userData->user_email."' AND `user_id`=".$user_id." AND `type`='deposit'");
		if( $type == 'total' ){
			$debitData = $wpdb->get_row("SELECT COALESCE(SUM(`withdrawal_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$userData->user_email."' AND `user_id`=".$user_id." AND `type`='withdrawal' AND `status`=2");
		}else{
			$debitData = $wpdb->get_row("SELECT COALESCE(SUM(`withdrawal_amount`),0) as `credit_amount` FROM $tableTransactionHistory WHERE `email`='".$userData->user_email."' AND `user_id`=".$user_id." AND `type`='withdrawal' AND (`status`=0 OR `status`=1 OR `status`=2)");
		}
		try {
			$final_amount = $creditData->credit_amount - $debitData->credit_amount;
		} catch (\Throwable $th) {
			$final_amount = 0;
		}
	} */
	return $final_amount;
}
add_action( 'wp_ajax_checkingCsrWDelivery', 'checkingCsrWDelivery_callback' );
function checkingCsrWDelivery_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRWalletDeliveryyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';

		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}

		$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		$filterByPoolRef = "";
		$filterByValuePoolRef = "";
		if( !empty( $filterByConditionsPoolRef ) ){
			$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
			if( $filterByPoolRef == 'is_exactly_simple' ){
				$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
			}else{
				$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
			}
		}

		$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
		$filterByDistributionWeek = "";
		$filterByValueDistributionWeek = "";
		if( !empty( $filterByConditionsDistributionWeek ) ){
			$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
			if( $filterByDistributionWeek == 'weeks_before' ){
				$filterByValueDistributionWeek = array();
				$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
				$fromweek = 1;
				$fromyear = 2022;
				$toweek = $givenWeeks[1];
				$toyear = $givenWeeks[0];
				$interval = new DateInterval('P7D');
				$start = (new \DateTime())->setISODate($fromyear, $fromweek);
				$end = (new \DateTime())->setISODate($toyear, $toweek);
				$period = new \DatePeriod($start, $interval, $end->add($interval));
				foreach($period as $date){
					$filterByValueDistributionWeek[] = $date->format('Y/W');
				}
			}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
				$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
			}else{
				$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
			}
		}

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}

		if( $filterByPoolRef != 'none' ){
			$filters['pool_ref'] = $filterByValuePoolRef;
		}

		if( $filterByDistributionWeek != 'none' ){
			$filters['text_10'] = $filterByValueDistributionWeek;
		}

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus AND `amount_due` > 0 $sessionDataQry");
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}/* else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else if( $filterKey == 'pool_ref' ){
					if( $filterByPoolRef != 'none' ){
						if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'text_10' ){
					if( $filterByDistributionWeek != 'none' ){
						if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		$total_amount_due = 0;
		$total_username = 0;
		$getAmountDue = $wpdb->get_row("SELECT SUM(`amount_due`) as `total_amount_due`, COUNT(DISTINCT `username`) AS `unique_usernames` FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		if( $getAmountDue ){
			$total_amount_due = $getAmountDue->total_amount_due;
			$total_username = $getAmountDue->unique_usernames;
		}
		if( $total_amount_due <= 0 ){
			$out = array( "error" => 1,'msg' => __('No CSR available for delivery with current selection.',CIP_TXTDOMAIN) ,'test' => "SELECT SUM(`amount_due`) as `total_amount_due` FROM $tableTokenHolder WHERE 1 $filter_qry AND `amount_due` > 0 $sessionDataQry" );
			echo wp_json_encode( $out );
			exit;
		}

		$tokenTypeArray = array();
		$tokenTypeText = "";
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
				$tokenTypeText = strtoupper( $getCurrentMember->token );
			}
		}

		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$html = "";
		ob_start();
		?>
		<form name="csrwalletdelivery_frm" id="csrwalletdelivery_frm">
			<div class="csr_delivery_summary_modal">
				<div class="d-flex" style="column-gap:30px;">
					<div>
						<h6 class="mb-1"><?php _e( $tokenTypeText . ' Delivery Summary', CIP_TXTDOMAIN ); ?></h6>
						<p class="text-left mb-1"> <?php _e('Rows to update: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_items ); ?></span> </p>
						<p class="text-left mb-1"> <?php _e('Number of members: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_username ); ?></span> </p>
						<p class="text-left mb-1"> <?php _e('Filtered Total Amount: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_amount_due ); ?></span> </p>
					</div>
				</div>
			</div>
			<input type="hidden" name="action" value="csrWalletDeliveryAction" />
			<input type="hidden" name="token" value="<?php echo $tokenTypeText; ?>" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyCSRWallertDeliveryyCSRX_') ?>" />
			<hr class="mt-1 mb-1">
			<div class="otp_section pb-3">
				<label for="sasm_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
				<input type="text" name="sasm_ga_otp" id="sasm_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
				<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
			</div>
			<input type="submit" class="btn btn-primary" name="submit" value="<?php _e('Submit', CIP_TXTDOMAIN); ?>" />
		</form>
		<div class="csrwalletdelivery_process_response mt-2"></div>
		<button type="button" class="btn btn-primary mt-2 wallet_delivery_complete_ok_btn" onclick="window.location.reload();" style="display:none;"><?php _e('OK', CIP_TXTDOMAIN); ?></button>
		<?php
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html, 'qry' => "SELECT SUM(`amount_due`) as `total_amount_due` FROM $tableTokenHolder WHERE 1 $filter_qry AND `amount_due` > 0 $sessionDataQry" );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_checkingCsrWDeliveryToSaving', 'checkingCsrWDeliveryToSaving_callback' );
function checkingCsrWDeliveryToSaving_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRWalletDeliverToSavingyyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';

		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}

		$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		$filterByPoolRef = "";
		$filterByValuePoolRef = "";
		if( !empty( $filterByConditionsPoolRef ) ){
			$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
			if( $filterByPoolRef == 'is_exactly_simple' ){
				$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
			}else{
				$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
			}
		}

		$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
		$filterByDistributionWeek = "";
		$filterByValueDistributionWeek = "";
		if( !empty( $filterByConditionsDistributionWeek ) ){
			$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
			if( $filterByDistributionWeek == 'weeks_before' ){
				$filterByValueDistributionWeek = array();
				$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
				$fromweek = 1;
				$fromyear = 2022;
				$toweek = $givenWeeks[1];
				$toyear = $givenWeeks[0];
				$interval = new DateInterval('P7D');
				$start = (new \DateTime())->setISODate($fromyear, $fromweek);
				$end = (new \DateTime())->setISODate($toyear, $toweek);
				$period = new \DatePeriod($start, $interval, $end->add($interval));
				foreach($period as $date){
					$filterByValueDistributionWeek[] = $date->format('Y/W');
				}
			}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
				$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
			}else{
				$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
			}
		}

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}

		if( $filterByPoolRef != 'none' ){
			$filters['pool_ref'] = $filterByValuePoolRef;
		}

		if( $filterByDistributionWeek != 'none' ){
			$filters['text_10'] = $filterByValueDistributionWeek;
		}

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus AND `saved_amount` > 0 $sessionDataQry");
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}/* else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else if( $filterKey == 'pool_ref' ){
					if( $filterByPoolRef != 'none' ){
						if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'text_10' ){
					if( $filterByDistributionWeek != 'none' ){
						if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `saved_amount` > 0 $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry $sessionDataQry");

		$tokenTypeArray = array();
		$tokenTypeText = "";

		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				if( empty( $getCurrentMember->saved_amount ) || $getCurrentMember->saved_amount <= 0 ){
					$out = array( "error" => 1,'msg' => __('Not all Rows have Saved Amounts. Please change the selection and try again.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				if( $getCurrentMember->corp_approved != 'Pending' ){
					$out = array( "error" => 1,'msg' => __('Not all Rows have Pending Status. Please change the selection and try again.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
				$tokenTypeText = strtoupper( $getCurrentMember->token );
			}
		}


		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$total_saved_amount = 0;
		$getAmountDue = $wpdb->get_row("SELECT SUM(`saved_amount`) as `total_saved_amount` FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `saved_amount` > 0 $sessionDataQry");
		if( $getAmountDue ){
			$total_saved_amount = $getAmountDue->total_saved_amount;
		}
		if( $total_saved_amount <= 0 ){
			$out = array( "error" => 1,'msg' => __('No '. $tokenTypeText .' available for deliver to saving with current selection.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$html = "";
		ob_start();
		?>
		<form name="csrwalletdeliverytosaving_frm" id="csrwalletdeliverytosaving_frm">
			<div class="csr_delivery_summary_modal">
				<div class="d-flex" style="column-gap:30px;">
					<div>
						<h6 class="mb-1"><?php _e( $tokenTypeText . ' Deliver to Saving Summary', CIP_TXTDOMAIN ); ?></h6>
						<p class="text-left mb-1"> <?php _e('Number of savings: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_items ); ?></span> </p>
						<p class="text-left mb-1"> <?php _e('Amount of '. $tokenTypeText .': ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_saved_amount ); ?></span> </p>
					</div>
				</div>
			</div>
			<input type="hidden" name="action" value="csrWalletDeliveryToSavingAction" />
			<input type="hidden" name="token" value="<?php echo $tokenTypeText; ?>" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyCSRWallertDeliveryToSavingCSRXy_') ?>" />
			<hr class="mt-1 mb-1">
			<div class="otp_section pb-3">
				<label for="sasm_ds_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
				<input type="text" name="sasm_ds_ga_otp" id="sasm_ds_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
				<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
			</div>
			<input type="submit" class="btn btn-primary" name="submit" value="<?php _e('Submit', CIP_TXTDOMAIN); ?>" />
		</form>
		<?php
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_checkingPrePartialCsrWDelivery', 'checkingPrePartialCsrWDelivery_callback' );
function checkingPrePartialCsrWDelivery_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckPrePartialCSRWalletDeliveryyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';

		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}

		$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		$filterByPoolRef = "";
		$filterByValuePoolRef = "";
		if( !empty( $filterByConditionsPoolRef ) ){
			$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
			if( $filterByPoolRef == 'is_exactly_simple' ){
				$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
			}else{
				$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
			}
		}

		$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
		$filterByDistributionWeek = "";
		$filterByValueDistributionWeek = "";
		if( !empty( $filterByConditionsDistributionWeek ) ){
			$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
			if( $filterByDistributionWeek == 'weeks_before' ){
				$filterByValueDistributionWeek = array();
				$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
				$fromweek = 1;
				$fromyear = 2022;
				$toweek = $givenWeeks[1];
				$toyear = $givenWeeks[0];
				$interval = new DateInterval('P7D');
				$start = (new \DateTime())->setISODate($fromyear, $fromweek);
				$end = (new \DateTime())->setISODate($toyear, $toweek);
				$period = new \DatePeriod($start, $interval, $end->add($interval));
				foreach($period as $date){
					$filterByValueDistributionWeek[] = $date->format('Y/W');
				}
			}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
				$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
			}else{
				$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
			}
		}

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}

		if( $filterByPoolRef != 'none' ){
			$filters['pool_ref'] = $filterByValuePoolRef;
		}

		if( $filterByDistributionWeek != 'none' ){
			$filters['text_10'] = $filterByValueDistributionWeek;
		}

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus AND `amount_due` > 0 $sessionDataQry");
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}/* else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else if( $filterKey == 'pool_ref' ){
					if( $filterByPoolRef != 'none' ){
						if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'text_10' ){
					if( $filterByDistributionWeek != 'none' ){
						if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");


		$tokenTypeArray = array();
		$tokenTypeText = "";
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
				$tokenTypeText = strtoupper( $getCurrentMember->token );
			}
		}

		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$partialDeliverIds = array();
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_WDSELECTION_PIC'));
				$partialDeliverIds[] = $rowEncryptId;
			}
		}
		$partialDeliverIdsString = "";
		if( count( $partialDeliverIds ) <= 15 && count( $partialDeliverIds ) > 0 ){
			$partialDeliverIdsString = implode(',', $partialDeliverIds);
		}else{
			$out = array( "error" => 1,'msg' => __('Partial Delivery only available for small delivery selections of under 15 rows.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$total_amount_due = 0;
		$getAmountDue = $wpdb->get_row("SELECT SUM(`amount_due`) as `total_amount_due` FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		if( $getAmountDue ){
			$total_amount_due = $getAmountDue->total_amount_due;
		}
		if( $total_amount_due <= 0 ){
			$out = array( "error" => 1,'msg' => __('No '. $tokenTypeText .' available for delivery with current selection.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'total' => count( $partialDeliverIds ), 'partialDeliverIds' => $partialDeliverIdsString );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_downloadingCsrWDelivery', 'downloadingCsrWDelivery_callback' );
function downloadingCsrWDelivery_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRWalletDeliveryyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		/* if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';

		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";

		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}

		$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		$filterByPoolRef = "";
		$filterByValuePoolRef = "";
		if( !empty( $filterByConditionsPoolRef ) ){
			$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
			if( $filterByPoolRef == 'is_exactly_simple' ){
				$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
			}else{
				$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
			}
		}

		$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
		$filterByDistributionWeek = "";
		$filterByValueDistributionWeek = "";
		if( !empty( $filterByConditionsDistributionWeek ) ){
			$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
			if( $filterByDistributionWeek == 'weeks_before' ){
				$filterByValueDistributionWeek = array();
				$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
				$fromweek = 1;
				$fromyear = 2022;
				$toweek = $givenWeeks[1];
				$toyear = $givenWeeks[0];
				$interval = new DateInterval('P7D');
				$start = (new \DateTime())->setISODate($fromyear, $fromweek);
				$end = (new \DateTime())->setISODate($toyear, $toweek);
				$period = new \DatePeriod($start, $interval, $end->add($interval));
				foreach($period as $date){
					$filterByValueDistributionWeek[] = $date->format('Y/W');
				}
			}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
				$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
			}else{
				$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
			}
		}

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}

		if( $filterByPoolRef != 'none' ){
			$filters['pool_ref'] = $filterByValuePoolRef;
		}

		if( $filterByDistributionWeek != 'none' ){
			$filters['text_10'] = $filterByValueDistributionWeek;
		}

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus AND `amount_due` > 0 $sessionDataQry");
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}/* else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else if( $filterKey == 'pool_ref' ){
					if( $filterByPoolRef != 'none' ){
						if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'text_10' ){
					if( $filterByDistributionWeek != 'none' ){
						if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry $sessionDataQry");
		$exportFile = fopen('php://memory', 'w');
		$columnHeader = array( 'reference', 'eth_address', 'occurs_times', 'csr_amount_initial', 'csramount_by_ethaddress', 'csr_amount_issued', 'amount_due', 'username', 'csramount_byusername', 'occurs_times_user', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', '_user_status', 'kyc_status', 'pool_ref', 'approvedkyc', 'corp_approved', 'notes_external', 'notes_internal', 'Position', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'note_1', 'note_2', 'note_3', 'note_4', 'note_5', 'note_6', 'note_7', 'note_8', 'note_9', 'note_10', 'imported_by', 'import_at', 'last_update_at', 'saved_amount', 'saving_date', 'saving_start_date', 'saving_interest', 'saving_periods', 'saving_state', 'sign_verify', 'transhash', 'contract_address', 'receiver_address', 'ma_enabled', 'token' );
		fputcsv($exportFile, $columnHeader);
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$redemption_date_formatted = "";
				if( $getCurrentMember->redemption_date ){
					$formattedRDate = DateTime::createFromFormat( 'd/m/Y', $getCurrentMember->redemption_date );
					if( $formattedRDate ){
						$redemption_date_formatted = $formattedRDate->format('d/m/Y');
					}
				}
				$claim_date_formatted = "";
				if( $getCurrentMember->claim_date ){
					$formattedCDate = DateTime::createFromFormat( 'd/m/Y', $getCurrentMember->claim_date );
					if( $formattedCDate ){
						$claim_date_formatted = $formattedCDate->format('d/m/Y');
					}
				}

				$rowData = array( $getCurrentMember->reference, $getCurrentMember->eth_address, $getCurrentMember->occurs_times, $getCurrentMember->csr_amount_initial, $getCurrentMember->csramount_by_ethaddress, $getCurrentMember->csr_amount_issued, $getCurrentMember->amount_due, $getCurrentMember->username, $getCurrentMember->csramount_byusername, $getCurrentMember->occurs_times_user, $getCurrentMember->first_name, $getCurrentMember->last_name, $redemption_date_formatted, $claim_date_formatted, $getCurrentMember->email, $getCurrentMember->_user_status, $getCurrentMember->kyc_status, $getCurrentMember->pool_ref, $getCurrentMember->approvedkyc, $getCurrentMember->corp_approved, $getCurrentMember->notes_external, $getCurrentMember->notes_internal, $getCurrentMember->position, $getCurrentMember->text_1, $getCurrentMember->text_2, $getCurrentMember->text_3, $getCurrentMember->text_4, $getCurrentMember->text_5, $getCurrentMember->text_6, $getCurrentMember->text_7, $getCurrentMember->text_8, $getCurrentMember->text_9, $getCurrentMember->text_10, $getCurrentMember->date_1, $getCurrentMember->date_2, $getCurrentMember->date_3, $getCurrentMember->date_4, $getCurrentMember->date_5, $getCurrentMember->date_6, $getCurrentMember->date_7, $getCurrentMember->date_8, $getCurrentMember->date_9, $getCurrentMember->date_10, $getCurrentMember->int_1, $getCurrentMember->int_2, $getCurrentMember->int_3, $getCurrentMember->int_4, $getCurrentMember->int_5, $getCurrentMember->int_6, $getCurrentMember->int_7, $getCurrentMember->int_8, $getCurrentMember->int_9, $getCurrentMember->int_10, $getCurrentMember->note_1, $getCurrentMember->note_2, $getCurrentMember->note_3, $getCurrentMember->note_4, $getCurrentMember->note_5, $getCurrentMember->note_6, $getCurrentMember->note_7, $getCurrentMember->note_8, $getCurrentMember->note_9, $getCurrentMember->note_10, $getCurrentMember->imported_by, $getCurrentMember->import_at, $getCurrentMember->last_update_at, $getCurrentMember->saved_amount, $getCurrentMember->saving_date, $getCurrentMember->saving_start_date, $getCurrentMember->saving_interest, $getCurrentMember->saving_periods, $getCurrentMember->saving_state, $getCurrentMember->sign_verify, $getCurrentMember->transhash, $getCurrentMember->contract_address, $getCurrentMember->receiver_address, $getCurrentMember->ma_enabled, $getCurrentMember->token );
				fputcsv($exportFile, $rowData);
			}
		}
		$current_user = wp_get_current_user();
		$logs = sprintf( __('CSR Wallet Delivery download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		fseek($exportFile, 0);
		$file_name = 'CSRHolder-'.date_i18n('d-m-Y H-i-s');
		header('content-type:application/csv;charset=UTF-8');
		header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
		fpassthru($exportFile);
		fclose($exportFile);
		exit;
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csrWalletDeliveryAction', 'csrWalletDeliveryAction_callback' );
function csrWalletDeliveryAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCSRWallertDeliveryyCSRX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){

		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

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

		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}

		$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		$filterByPoolRef = "";
		$filterByValuePoolRef = "";
		if( !empty( $filterByConditionsPoolRef ) ){
			$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
			if( $filterByPoolRef == 'is_exactly_simple' ){
				$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
			}else{
				$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
			}
		}

		$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
		$filterByDistributionWeek = "";
		$filterByValueDistributionWeek = "";
		if( !empty( $filterByConditionsDistributionWeek ) ){
			$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
			if( $filterByDistributionWeek == 'weeks_before' ){
				$filterByValueDistributionWeek = array();
				$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
				$fromweek = 1;
				$fromyear = 2022;
				$toweek = $givenWeeks[1];
				$toyear = $givenWeeks[0];
				$interval = new DateInterval('P7D');
				$start = (new \DateTime())->setISODate($fromyear, $fromweek);
				$end = (new \DateTime())->setISODate($toyear, $toweek);
				$period = new \DatePeriod($start, $interval, $end->add($interval));
				foreach($period as $date){
					$filterByValueDistributionWeek[] = $date->format('Y/W');
				}
			}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
				$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
			}else{
				$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
			}
		}

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}

		if( $filterByPoolRef != 'none' ){
			$filters['pool_ref'] = $filterByValuePoolRef;
		}

		if( $filterByDistributionWeek != 'none' ){
			$filters['text_10'] = $filterByValueDistributionWeek;
		}

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}/* else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else if( $filterKey == 'pool_ref' ){
					if( $filterByPoolRef != 'none' ){
						if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'text_10' ){
					if( $filterByDistributionWeek != 'none' ){
						if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
		}

		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry ORDER BY `id` ASC");
		$tokenTypeArray = array();
		$tokenTypeText = "";
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
				$tokenTypeText = strtoupper( $getCurrentMember->token );
			}
		}

		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( isset( $_POST['get_wallet_delivery_data'] ) && $_POST['get_wallet_delivery_data'] == 'yes' ){

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

					$_SESSION['wallet_delivery_ga_otp'] = $_POST['sasm_ga_otp'];

					$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry");
					$per_page = 1000;
					$total_paged = ceil( $total_items / $per_page );

					$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Wallet deliveries started...',CIP_TXTDOMAIN), 'msg2' => __('Wallet deliveries started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to deliver', CIP_TXTDOMAIN),$total_items ) );
				}else{
					$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

		}else if( isset( $_POST['wallet_delivering_data'] ) && $_POST['wallet_delivering_data'] == 'yes' ){

			if( !empty( $_POST['sasm_ga_otp'] ) && !empty( $_SESSION['wallet_delivery_ga_otp'] ) ){
				if( $_SESSION['wallet_delivery_ga_otp'] == $_POST['sasm_ga_otp'] ){

					$per_page = 1000;
					$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;

					$error = 0;
					$rowDataCount= 0;
					$countError = 0;
					$countSuccess = 0;
					$insertingCount = 0;

					$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 = __('Deposit', CIP_TXTDOMAIN);
					$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `amount_due` > 0 $sessionDataQry ORDER BY `id` ASC LIMIT ".$per_page."");
					$total_amount_due_deliver = 0;
					if( $getCurrentMembers ){
						$withdrawLoop = 1;
						$deliveryBatchId = get_option('delivery_batch_id');
						if( !empty( $deliveryBatchId ) ){
							$deliveryBatchId = $deliveryBatchId + 1;
						}else{
							$deliveryBatchId = 1;
						}
						$withdrawBatchUpdate = false;
						$withdrawReference = uniqidReal();
						foreach( $getCurrentMembers as $getCurrentMember ){
							$short_description = "";
							$csr_amount_issued = $getCurrentMember->csr_amount_issued;
							$amount_due = $getCurrentMember->amount_due;
							if( $amount_due > 0 ){
								$deliveryID = sprintf('%04d', $withdrawLoop);
								// $note_8 = sprintf('%04d', $deliveryBatchId) . '-' . date_i18n('Y-m-d') . '-' . $deliveryID;
								$note_8 = $deliveryBatchId;
								// $note_9 = $withdrawReference;
								$poolPatternMpp  = "/^MPP-(.*?)/i";
								$notePatternMpp  = "/^Your application to join the purchase pool is accepted. Your share in (.*?) is (.*?) Euros./i";
								$updateNoteArr = array();
								$rowNotes = explode("|", $getCurrentMember->notes_external);
								if( !empty( $rowNotes ) ){
									foreach( $rowNotes as $rowNote){
										$rowNote = trim( $rowNote );
										if( !empty( $rowNote ) ){
											$updateNoteArr[] = $rowNote;
										}
									}
								}

								//short description
								$awardDeliveryPool = array( 'C', 'F', 'J', 'H' );
								$csrRedemptionDelivery = array( 'A', 'B', 'D', 'E' );

								$csrDelivery = array( 'G','K', 'DI', 'BNS' );
								$csrDeliveryWeekPattern = "/^Week-(.*?)/i";
								$csrDeliveryMonthYear = array(
									"/^January_[0-9]{4}/i",
									"/^February_[0-9]{4}/i",
									"/^March_[0-9]{4}/i",
									"/^April_[0-9]{4}/i",
									"/^May_[0-9]{4}/i",
									"/^June_[0-9]{4}/i",
									"/^July_[0-9]{4}/i",
									"/^August_[0-9]{4}/i",
									"/^September_[0-9]{4}/i",
									"/^October_[0-9]{4}/i",
									"/^November_[0-9]{4}/i",
									"/^December_[0-9]{4}/i",
								);

								$csrSpecialPoolsPattern  = "/^SPC-(.*?)/i";

								if( preg_match($poolPatternMpp, $getCurrentMember->pool_ref ) ){
									$short_description = __( 'Bonus Purchase Pool delivery', CIP_TXTDOMAIN );
								}else if( in_array( $getCurrentMember->pool_ref, $awardDeliveryPool ) ){
									$short_description = __( 'Discretionary award delivery', CIP_TXTDOMAIN );
								}else if( in_array( $getCurrentMember->pool_ref, $csrRedemptionDelivery ) ){
									$short_description = __( $tokenTypeText . ' redemption delivery', CIP_TXTDOMAIN );
								}else if(
									in_array( $getCurrentMember->pool_ref, $csrDelivery ) ||
									preg_match($csrDeliveryWeekPattern, $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[0], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[1], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[2], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[3], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[4], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[5], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[6], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[7], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[8], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[9], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[10], $getCurrentMember->pool_ref ) ||
									preg_match($csrDeliveryMonthYear[11], $getCurrentMember->pool_ref )
								){
									$short_description = __( $tokenTypeText . ' delivery', CIP_TXTDOMAIN );
								}else if( $getCurrentMember->pool_ref == 'SPC-CRSM' ){
									$short_description = __( 'Partial delivery', CIP_TXTDOMAIN );
								}else if( preg_match( $csrSpecialPoolsPattern, $getCurrentMember->pool_ref ) && $getCurrentMember->pool_ref != 'SPC-CRSM' ){
									$short_description = __( $tokenTypeText . ' redemption delivery', CIP_TXTDOMAIN );
								}else if( in_array( 'Pending 10% distribution.', $updateNoteArr ) || in_array( 'Pending 10% distribution', $updateNoteArr ) ){
									$short_description = __( 'PNP delivery', CIP_TXTDOMAIN );
								}else{
									$short_description = __( 'Delivery', CIP_TXTDOMAIN );
								}

								if( preg_match($poolPatternMpp, $getCurrentMember->pool_ref ) ){ // MPP specific note remove
									if( !empty( $updateNoteArr ) ){
										foreach( $updateNoteArr as $key => $updateNote ){
											  if( preg_match($notePatternMpp, $updateNote ) ){
												unset( $updateNoteArr[ $key ] );
											}
										}
									}
								}else{	//pending distribution, remainder allocation note remove
									if( !empty( $updateNoteArr ) ){
										foreach( $updateNoteArr as $key => $updateNote ){
											if( $updateNote == 'Pending 10% distribution.' || $updateNote == 'Remainder of CSR allocation (90%).' ){
												unset( $updateNoteArr[ $key ] );
											}
										}
									}
								}


								$notesString = "";
								$updateNoteArr = array_unique($updateNoteArr);
								if( !empty( $updateNoteArr ) ){
									foreach( $updateNoteArr as $updateNoteArrVal ){
										$notesString .= '| '. $updateNoteArrVal .' |';
									}
									$notesString = notes_trim_pipe( $notesString );
								}
								if( $getCurrentMember->pool_ref == 'SPC-CRSM' ){
									$updateDataArr = ['csr_amount_issued' => $amount_due, 'amount_due' => 0, 'corp_approved' => 'Delivered', 'date_1' => date_i18n('d/m/Y'), 'last_update' => date_i18n('Y-m-d H:i:s'), 'note_8' => $note_8, 'text_9' => 'management'];
								}else if( preg_match($poolPatternMpp, $getCurrentMember->pool_ref ) ){
									$updateDataArr = ['csr_amount_issued' => $amount_due, 'amount_due' => 0, 'corp_approved' => 'Delivered', 'date_1' => date_i18n('d/m/Y'), 'last_update' => date_i18n('Y-m-d H:i:s'), 'note_8' => $note_8, 'text_2' => '', 'notes_external' => $notesString ];
								}else{
									$updateDataArr = ['csr_amount_issued' => $amount_due, 'amount_due' => 0, 'corp_approved' => 'Delivered', 'date_1' => date_i18n('d/m/Y'), 'last_update' => date_i18n('Y-m-d H:i:s'), 'note_8' => $note_8, 'text_2' => '', 'notes_external' => $notesString ];
								}
								$update = $wpdb->update(
									$tableTokenHolder,
									// ['notes_external' => '', 'csr_amount_issued' => $amount_due, 'amount_due' => 0, 'corp_approved' => 'Issued', 'date_1' => date_i18n('d/m/Y'), 'last_update' => date_i18n('Y-m-d H:i:s'), 'note_8' => $note_8, 'note_9' => $note_9 ],
									$updateDataArr,
									['id' => $getCurrentMember->id]
								);
								if( $update ){
									$total_amount_due_deliver += $amount_due;
									$logs = sprintf( __( $tokenTypeText . ' Wallet Delivered. username: %s, email: %s, reference: %s, csr_amount_issued: %s by %s at %s', 'corsair-login'), $getCurrentMember->username, $getCurrentMember->email, $getCurrentMember->reference, $amount_due, $current_user->user_email, date_i18n('d/m/Y H:i A') );
									create_cip_logs_entery( $user_id, 'wallet_delivery', '','sm', $logs, true  );
									$userData = get_user_by('email', $getCurrentMember->email);
									$user_id = 0;
									if( $userData ){
										$user_id = $userData->ID;
									}
									$transactionData = array(
										'user_id'			=>	$user_id,
										'txn_id'			=>	$getCurrentMember->reference,
										'email'				=>	$getCurrentMember->email,
										'username'			=>	$getCurrentMember->username,
										'withdrawal_amount'	=>	0,
										'received_amount'	=>	$amount_due,
										'withdrawal_fee'	=>	0,
										'type'				=>	'deposit',
										'description'		=>	$logs,
										'short_description'	=>	$short_description,
										'_date'				=>	date_i18n('Y-m-d H:i:s'),
										'status'			=>	0,
										'token'				=>	$getCurrentMember->token
									);
									$transInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );
									$withdrawBatchUpdate = true;
									$withdrawLoop++;

									//notice of withdrawal request
									$tableCipNotice = $wpdb->prefix.'cip_notice';
									$notificationMessageText = sprintf( __('%s '. $tokenTypeText .' successfully deposited to your CSR wallet.', CIP_TXTDOMAIN), number_format( $amount_due, 2 ) );
									$noticeData = array(
										"email"		=>	$getCurrentMember->email,
										"username"	=>	'',
										"notice"	=>	$notificationMessageText,
										"status"	=>	1,
										"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
									);
									$wpdb->insert( $tableCipNotice, $noticeData );
									$messageText = sprintf( __('<p class="text-left text-size-18">Your '. $tokenTypeText .' wallet has received a %s '. $tokenTypeText .' deposit.</p><p class="text-left text-size-18"><b>Transaction Reference: %s</b></p>', CIP_TXTDOMAIN), number_format( $amount_due, 2), $getCurrentMember->reference );
									$message = sprintf( __('<h2>Dear Member,</h2><h3>%s', CIP_TXTDOMAIN), $messageText );
									$htmlContent = mailTemplateHtmlRender( $message );
									if( get_email_send_toggle('deposit') == 1 ){
										wp_mail( $getCurrentMember->email, $subject, $htmlContent );
									}
									$insertingCount++;
								}
							}
						}

						$session_total_amount_due_deliver = ( isset( $_SESSION['total_amount_due_deliver'] ) ) ? $_SESSION['total_amount_due_deliver'] : 0;
						$_SESSION['total_amount_due_deliver'] = $total_amount_due_deliver + $session_total_amount_due_deliver;

						if( $_POST['total_paged'] == $_POST['page_id'] ){

							$out = array( "error" => 0,'msg' => sprintf( __('<br/>Delivered : %s',CIP_TXTDOMAIN), $insertingCount ), 'isLastPage' => 'yes', 'msg2' => __( $tokenTypeText .' Wallet Delivered.',CIP_TXTDOMAIN) );

							$_SESSION['wallet_delivery_ga_otp'] = "";

							if( $withdrawBatchUpdate ){

								$content = sprintf(__('Batch delivery of %s '. $tokenTypeText .' performed by %s.', CIP_TXTDOMAIN), number_format( $_SESSION['total_amount_due_deliver'] ), $current_user->user_email );
								create_cip_logs_entery( $user_id, 'wallet_delivery', '','sm', $content, true  );

								if( get_sms_send_toggle('batch_delivery') == 1 ){
									$content = sprintf(__('Batch delivery of %s '. $tokenTypeText .' performed by %s.', CIP_TXTDOMAIN), number_format( $_SESSION['total_amount_due_deliver'] ), $current_user->user_email );
									create_cip_logs_entery( $user_id, 'wallet_delivery', '','sm', $content, true  );
									brevo_sms_alert_send( $content );
								}
								update_option( 'delivery_batch_id', $deliveryBatchId );
							}

						}else{
							$out = array( "error" => 0,'msg' => sprintf( __('<br/>Delivered : %s',CIP_TXTDOMAIN), $insertingCount ), 'isLastPage' => 'no' );
						}

					}
				}else{
					$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}


	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csrWalletDeliveryToSavingAction', 'csrWalletDeliveryToSavingAction_callback' );
function csrWalletDeliveryToSavingAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCSRWallertDeliveryToSavingCSRXy_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		}
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( !empty( $_POST['sasm_ds_ga_otp'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ds_ga_otp'], 0) ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
				$filter_qry = "";
				$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
				$filterBy = "";
				$filterByValue = "";
				if( !empty( $filterByConditions ) ){
					$filterBy = $filterByConditions['filter_condition_type'];
					$filterByValue = $filterByConditions['filter_condition_value'];
				}

				$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
				$filterByPoolRef = "";
				$filterByValuePoolRef = "";
				if( !empty( $filterByConditionsPoolRef ) ){
					$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_ref'];
					if( $filterByPoolRef == 'is_exactly_simple' ){
						$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_ref_bulk'] ) );
					}else{
						$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_ref'];
					}
				}

				$filterByConditionsDistributionWeek = json_decode( stripslashes( $_REQUEST['filterByConditionDistributionWeek'] ), true );
				$filterByDistributionWeek = "";
				$filterByValueDistributionWeek = "";
				if( !empty( $filterByConditionsDistributionWeek ) ){
					$filterByDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_type_distribution_week'];
					if( $filterByDistributionWeek == 'weeks_before' ){
						$filterByValueDistributionWeek = array();
						$givenWeeks = explode('/', $filterByConditionsDistributionWeek['filter_condition_value_distribution_week_before']);
						$fromweek = 1;
						$fromyear = 2022;
						$toweek = $givenWeeks[1];
						$toyear = $givenWeeks[0];
						$interval = new DateInterval('P7D');
						$start = (new \DateTime())->setISODate($fromyear, $fromweek);
						$end = (new \DateTime())->setISODate($toyear, $toweek);
						$period = new \DatePeriod($start, $interval, $end->add($interval));
						foreach($period as $date){
							$filterByValueDistributionWeek[] = $date->format('Y/W');
						}
					}else if( $filterByDistributionWeek == 'is_exactly_simple' ){
						$filterByValueDistributionWeek = array_filter( explode(',', $filterByConditionsDistributionWeek['filter_condition_value_distribution_bulk'] ) );
					}else{
						$filterByValueDistributionWeek = $filterByConditionsDistributionWeek['filter_condition_value_distribution_week'];
					}
				}

				$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
				$filterByUsername = "";
				$filterByValueUsername = "";
				if( !empty( $filterByConditionsUsername ) ){
					$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
					if( $filterByUsername == 'is_exactly_simple' ){
						$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
					}else{
						$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
					}
				}
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				if( $filterBy != 'none' ){
					$filters['notes_external'] = trim( $filterByValue );
				}

				if( $filterByPoolRef != 'none' ){
					$filters['pool_ref'] = $filterByValuePoolRef;
				}

				if( $filterByDistributionWeek != 'none' ){
					$filters['text_10'] = $filterByValueDistributionWeek;
				}

				if( $filterByUsername != 'none' ){
					$filters['username'] = $filterByValueUsername;
				}
				$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
				$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}/* else if( $filterKey == 'username' ){
							$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
						} */else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else if( $filterKey == 'notes_external' ){
							if( $filterBy != 'none' ){
								if( $filterBy == 'is_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
								}else if( $filterBy == 'is_not_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
								}else if( $filterBy == 'contains_text' ){
									$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'does_not_contains_text' ){
									$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'starts_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
								}else if( $filterBy == 'ends_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
								}else if( $filterBy == 'is_exactly' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
								}
							}
						}else if( $filterKey == 'pool_ref' ){
							if( $filterByPoolRef != 'none' ){
								if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
									$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
								}
							}
						}else if( $filterKey == 'text_10' ){
							if( $filterByDistributionWeek != 'none' ){
								if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
									$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
								}
							}
						}else if( $filterKey == 'username' ){
							if( $filterByUsername != 'none' ){
								if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
									$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
								}
							}
						}else if( $filterKey == 'token' ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else{
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}

				$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 = __('Deposit', CIP_TXTDOMAIN);

				$tokenTypeArray = array();
				$tokenTypeText = "";

				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry $sessionDataQry");
				if( $getCurrentMembers ){
					foreach( $getCurrentMembers as $getCurrentMember ){
						if( empty( $getCurrentMember->saved_amount ) || $getCurrentMember->saved_amount <= 0 ){
							$out = array( "error" => 1,'msg' => __('Not all Rows have Saved Amounts. Please change the selection and try again.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						if( $getCurrentMember->corp_approved != 'Pending' ){
							$out = array( "error" => 1,'msg' => __('Not all Rows have Pending Status. Please change the selection and try again.',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
						$tokenTypeText = strtoupper( $getCurrentMember->token );
					}
				}

				if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
					$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}

				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $whereStatus $filter_qry AND `saved_amount` > 0 $sessionDataQry");
				$total_amount_due_deliver = 0;
				if( $getCurrentMembers ){
					$withdrawLoop = 1;
					$deliveryBatchId = get_option('delivery_batch_id');
					if( !empty( $deliveryBatchId ) ){
						$deliveryBatchId = $deliveryBatchId + 1;
					}else{
						$deliveryBatchId = 1;
					}
					$withdrawBatchUpdate = false;
					$withdrawReference = uniqidReal();
					foreach( $getCurrentMembers as $getCurrentMember ){
						$csr_amount_issued = $getCurrentMember->csr_amount_issued;
						$amount_due = $getCurrentMember->amount_due;
						if( $amount_due > 0 ){
							$deliveryID = sprintf('%04d', $withdrawLoop);
							// $note_8 = sprintf('%04d', $deliveryBatchId) . '-' . date_i18n('Y-m-d') . '-' . $deliveryID;
							$note_8 = $deliveryBatchId;
							// $note_9 = $withdrawReference;
							$updateNoteArr = array();
							/* $rowNotes = explode("|", $getCurrentMember->notes_external);
							if( !empty( $rowNotes ) ){
								foreach( $rowNotes as $rowNote){
									$rowNote = trim( $rowNote );
									if( !empty( $rowNote ) ){
										$updateNoteArr[] = $rowNote;
									}
								}
							} */
							$updateNoteArr[] = 'Saved ' . $tokenTypeText;
							$notesString = "";
							$updateNoteArr = array_unique($updateNoteArr);
							if( !empty( $updateNoteArr ) ){
								foreach( $updateNoteArr as $updateNoteArrVal ){
									$notesString .= '| '. $updateNoteArrVal .' |';
								}
								$notesString = notes_trim_pipe( $notesString );
							}
							$update = $wpdb->update(
								$tableTokenHolder,
								['csr_amount_issued' => $amount_due, 'amount_due' => 0, 'corp_approved' => 'Saved ' . $tokenTypeText, 'notes_external' => $notesString, 'text_2' => '', 'date_1' => date_i18n('d/m/Y'), 'saving_start_date' => date_i18n('d/m/Y'), 'last_update' => date_i18n('Y-m-d H:i:s'), 'note_8' => $note_8 ],
								['id' => $getCurrentMember->id, 'corp_approved' => 'Pending']
							);
							if( $update ){
								$withdrawBatchUpdate = true;
								$logs = sprintf( __( $tokenTypeText . ' Wallet Deliver to Saved. username: %s, email: %s, reference: %s, csr_amount_issued: %s by %s at %s. Batch ID: %s', 'corsair-login'), $getCurrentMember->username, $getCurrentMember->email, $getCurrentMember->reference, $amount_due, $current_user->user_email, date_i18n('d/m/Y H:i A'), $deliveryBatchId );
								create_cip_logs_entery( $user_id, 'wallet_delivery', '','sm', $logs, true  );
								$userData = get_user_by('email', $getCurrentMember->email);
								$user_id = 0;
								if( $userData ){
									$user_id = $userData->ID;
								}
								$withdrawLoop++;
							}
						}
					}
					if( $withdrawBatchUpdate ){
						update_option( 'delivery_batch_id', $deliveryBatchId );
					}
					$out = array( "error" => 0,'msg' => __( $tokenTypeText . ' Wallet Deliver to Saved',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_check_for_smsa_ga_twofa', 'check_for_smsa_ga_twofa_cb');
function check_for_smsa_ga_twofa_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	$nonceCheck = '';
	$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'delivery' || $_POST['thisType'] == 'login' ) ) ? $_POST['thisType'] : '-';
	if( $thisType == 'login' ){
		$nonceCheck = '_SMSALOGIN2FAMicro_';
	}else if( $thisType == 'delivery' ){
		$nonceCheck = '_WalletDelivery2FAMicro_';
	}
	if( wp_verify_nonce( $_POST['_micro'], $nonceCheck ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$logType = '-';
		if( current_user_can( 'supportagent' ) ){
			$logType = 'sa';
		}else if( current_user_can( 'supportmanager' ) ){
			$logType = 'sm';
		}
		$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( $google_auth_key ) ){
			$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'isopen' => 0 );
			/* if( $thisType == 'delivery' ){
				update_user_meta( $user_id, 'google_auth_key_walletdelivery', 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_cip_logs_entery( $user_id, 'profile', '',$logType, $logs, true  ); */
		}else{
			$out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'isopen' => 1 );
		}
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_googleAuth2FAWalletDeliveryactivationAct', 'corsair_login_googleAuth2FAWalletDeliveryactivationAct_callback' );
function corsair_login_googleAuth2FAWalletDeliveryactivationAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPGoogleAuthenticatorWalletDeliveryEnablingCIP_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) || current_user_can( 'administrator' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'delivery' || $_POST['thisType'] == 'login' ) ) ? $_POST['thisType'] : '-';
		$logType = '-';
		if( current_user_can( 'supportagent' ) ){
			$logType = 'sa';
		}else if( current_user_can( 'supportmanager' ) ){
			$logType = 'sm';
		}else if( current_user_can( 'administrator' ) ){
			$logType = 'admin';
		}
		// if( isset( $_POST['thisType'] ) && ( $thisType == 'delivery' || $thisType == 'login' ) ){
			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'] );
						$_SESSION['google_auth_key'] = "";
						unset( $_SESSION['google_auth_key'] );

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

						$logs = sprintf( __('2FA google authenticator activated by %s at %s', 'corsair-login'), $current_user->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( $user_id, 'profile', '',$logType, $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 or 6-digit code to continue.','corsair-login') );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Please enter valid backup key or 6-digit code to continue.','corsair-login') );
			}
		// }
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_toggle_for_smsa_ga_twofa', 'toggle_for_smsa_ga_twofa');
function toggle_for_smsa_ga_twofa(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) && wp_verify_nonce( $_POST['_micro'],'_CL_Toogle2FAMicroSaSm_LC_' ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'delivery' || $_POST['thisType'] == 'login' ) ) ? $_POST['thisType'] : '-';
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$logType = '-';
		if( current_user_can( 'supportagent' ) ){
			$logType = 'sa';
		}else if( current_user_can( 'supportmanager' ) ){
			$logType = 'sm';
		}
		if( !empty( $_POST['code'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['code'], 0) ){
				if( $thisType == 'delivery' ){

					if( $_POST['thisToggle'] == 1 ){
						$out = array( "error" => 0,'msg' => __('Google 2FA activated','corsair-login'), 'thisType' => $thisType, 'thisToggle' => $_POST['thisToggle'] );
						update_user_meta( $user_id, 'google_auth_key_walletdelivery', 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') );
					}else if( $_POST['thisToggle'] == 0 ){
						delete_user_meta( $user_id, 'google_auth_key_walletdelivery' );
						$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') );
						$out = array( "error" => 0,'msg' => __('Google 2FA deactivated','corsair-login'), 'thisType' => $thisType, 'thisToggle' => $_POST['thisToggle'] );
					}
					create_cip_logs_entery( $user_id, 'profile', '',$logType, $logs, true  );
				}else if( $thisType == 'login' ){

					if( $_POST['thisToggle'] == 1 ){
						$out = array( "error" => 0,'msg' => __('Google 2FA activated','corsair-login'), 'thisType' => $thisType, 'thisToggle' => $_POST['thisToggle'] );
						update_user_meta( $user_id, 'google_auth_key_login', 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') );
					}else if( $_POST['thisToggle'] == 0 ){
						delete_user_meta( $user_id, 'google_auth_key_login' );
						$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') );
						$out = array( "error" => 0,'msg' => __('Google 2FA deactivated','corsair-login'), 'thisType' => $thisType, 'thisToggle' => $_POST['thisToggle'] );
					}
					create_cip_logs_entery( $user_id, 'profile', '',$logType, $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_disable_for_smsa_ga_twofa', 'disable_for_smsa_ga_twofa_cb');
function disable_for_smsa_ga_twofa_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) && wp_verify_nonce( $_POST['_micro'],'_CL_Toogle2FAMicroSaSm_LC_' ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$thisType = ( isset( $_POST['thisType'] ) && ( $_POST['thisType'] == 'delivery' ) ) ? $_POST['thisType'] : '-';
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$logType = '-';
		if( current_user_can( 'supportagent' ) ){
			$logType = 'sa';
		}else if( current_user_can( 'supportmanager' ) ){
			$logType = 'sm';
		}
		if( !empty( $_POST['code'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['code'], 0) ){
				$out = array( "error" => 0,'msg' => __('Google 2FA (CSR Wallet Delivery and some other secure activities are disabled for 1 working day after Google 2FA is disabled)','corsair-login'), 'thisType' => $thisType );
				if( $thisType == 'delivery' ){
					delete_user_meta( $user_id, 'google_auth_key_walletdelivery' );
				}
				$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_cip_logs_entery( $user_id, 'profile', '',$logType, $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_SmSagoogleAuth2FADeactivateAct', 'corsair_login_SmSagoogleAuth2FADeactivateAct_callback' );
function corsair_login_SmSagoogleAuth2FADeactivateAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPSmSaGoogleAuthenticatorDisablingCIP_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$logType = '-';
		if( current_user_can( 'supportagent' ) ){
			$logType = 'sa';
		}else if( current_user_can( 'supportmanager' ) ){
			$logType = 'sm';
		}
		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_walletdelivery' );
				delete_user_meta( $user_id, 'google_auth_key_login' );
				$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_cip_logs_entery( $user_id, 'profile', '', $logType, $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;
}
//5759
add_action('wp_ajax_toggleWithdrawalSuspensionAction', 'toggleWithdrawalSuspensionAction_callback');
function toggleWithdrawalSuspensionAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_YxWithdrawalSuspensionTogglexY_' ) && current_user_can( 'member' ) ){
		global $wpdb;
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( $_POST['toggleValue'] == 0 ){
			$tableKycData = $wpdb->prefix.'kyc_data';
			$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
			$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
			$checkKycStatus = $wpdb->get_row("SELECT * FROM $tableKycData WHERE $whereEmail AND `status`='approved'");
			if( $checkKycStatus ){
				$clientResendKey = 'resend_attempt_disable_withdraw_suspension' . $client_ip_address;
				if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
					if ((get_transient($clientResendKey) !== false)) {
						$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
						wp_send_json($out);
						exit;
					}
				}
				$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$google_auth_key_withdrawal = get_user_meta( $user_id, 'google_auth_key_withdrawal', true );
				$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_withdrawal == 1 ) ? 1 : 0;

				if( $corsair_2fa_ga != 'yes' || $ga2fa_login_enabled != 1 ){
					$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
					wp_send_json($out);
					exit;
				}
				$otpContent = "";
				$otpGAContent = "";
				$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_disable_withdrawal_suspension', $user_otp );
				update_user_meta( $user_id, 'user_otp_disable_withdrawal_suspension_expiration', $user_otp_expiration );
				$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(__("%s - Email OTP Verification for Disable Withdrawal Suspension", 'corsair-login'), $blogname);
				$message = __('<h2>Confirm Disable Withdrawal Suspension</h2>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
				$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
				$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
				$htmlContent = mailTemplateHtmlRender( $message );
				$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
				if( $sent_mail ){
					$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
					set_transient($clientResendKey, '1', 60);
					ob_start();
					?>
					<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
					<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 mb-1" 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>
					<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_disable_withdraw_suspension" 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_disable_withdraw_suspension').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_disable_withdraw_suspension').text("Resend in "+(sec)+' s')
									}else{
										$('#resend_disable_withdraw_suspension').attr('data-stat','').removeClass('disabled').text('Resend OTP')
										clearInterval(countdown)
									}
								}, 1000);
							}
						});
					</script>
					<?php
					$otpContent = ob_get_clean();
					ob_start();
					?>
					<hr class="mt-4 mb-3">
					<div class="otp_section pb-3">
						<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
						<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
						<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
					</div>
					<?php
					$otpGAContent = ob_get_clean();
					$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'otpContent' => $otpContent, 'otpGAContent' => $otpGAContent, 'isopen' => 1 );
				}
				/* $dobLabel = "";
				$dobLabelInfo = "";
				if( $checkKycStatus->account_type == 'business' ){
					$dobLabel = __("Business Owner Date Of Birth", CIP_TXTDOMAIN);
					$dobLabelInfo = ' <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="'. __('Business owner date of birth used when KYB submitted.', CIP_TXTDOMAIN).'"></i>';
				}else{
					$dobLabel = __("Date Of Birth", CIP_TXTDOMAIN);
					$dobLabelInfo = ' <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="'. __('Date of birth used when KYC submitted.', CIP_TXTDOMAIN).'"></i>';
				}

				$numberLabel = "";
				$numberLabelInfo = "";
				if( $checkKycStatus->account_type == 'business' ){
					$numberLabel = __("Business Registration Number", CIP_TXTDOMAIN);
					$numberLabelInfo = ' <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="'. __('Business registration number used when KYB submitted.', CIP_TXTDOMAIN).'"></i>';
				}else{
					$numberLabel = __("Document Number", CIP_TXTDOMAIN);
					$numberLabelInfo = ' <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="'. __('Passport, Government issued ID card, Driving license or Other ID number used when KYC submitted.', CIP_TXTDOMAIN).'"></i>';
				}
				$html = "";
				ob_start();
				?>
				<form class="disable_withdrawal_suspension_kyc" id="disable_withdrawal_suspension_kyc">
					<h6><?php _e('Disable Security - Withdrawal suspension', CIP_TXTDOMAIN); ?></h6>
					<div class="form-group">
						<label for="kyc_dob"><?php echo $dobLabel; ?> <?php echo $dobLabelInfo; ?></label>
						<div class="input-group-append align-items-center">
							<input type="text" class="form-control mb-0" id="kyc_dob" name="kyc_dob" placeholder="dd/mm/yyyy" />
							<label for="kyc_dob" class="input-group-addon pl-1 pr-1" style="cursor:pointer;"><span><i class="fa fa-calendar-alt" aria-hidden="true"></i></span></label>
						</div>
					</div>
					<div class="form-group">
						<label for="kyc_number"><?php echo $numberLabel; ?> <?php echo $numberLabelInfo; ?></label>
						<input type="text" class="form-control mb-0" id="kyc_number" name="kyc_number" />
					</div>
					<input type="hidden" name="action" value="disable_withdrawal_suspension_kyc_verification_act" />
					<input type="hidden" name="_micro" value="<?php echo wp_create_nonce( '_DisableWithdrawalSuspension_' ); ?>" />
					<input type="submit" name="submit" value="<?php _e('Submit', CIP_TXTDOMAIN); ?>" style="padding: 10px 20px !important;" />
				</form>
				<?php
				$html .= ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Verification','corsair-login'), 'isopen' => 1, 'html' => $html ); */
			}else{
				$out = array( "error" => 1,'msg' => __('You must complete the KYC process to continue.','corsair-login') );
				wp_send_json($out);
				exit;
			}
		}else{
			update_user_meta( $user_id, 'withdrawal_suspension_5_minute', 'enable' );
			$out = array( "error" => 0,'msg' => __('Enabled','corsair-login'), 'isopen' => 0 );
			$current_user = wp_get_current_user();
			$logs = sprintf( __('Withdrawal suspension for a minutes after login enabled by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'profile', '','member', $logs, true );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_disable_withdrawal_suspension_act', 'disable_withdrawal_suspension_act_callback');
function disable_withdrawal_suspension_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIP321_DISABLE_WITHDRAWAL_SUSPENSION_123PIC_' ) && current_user_can( 'member' ) ){
		global $wpdb;
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$tableKycData = $wpdb->prefix.'kyc_data';
		$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
		$checkKycStatus = $wpdb->get_row("SELECT * FROM $tableKycData WHERE $whereEmail AND `status`='approved'");
		$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
		$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
		if( $decryptedUserId == $user_id ){
			$user_otp = get_user_meta( $user_id, 'user_otp_disable_withdrawal_suspension', true );
			$user_otp_expiration = get_user_meta( $user_id, 'user_otp_disable_withdrawal_suspension_expiration', true );
			$emailOTPValid = false;
			$gaOTPValid = false;
			if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
				$emailOTPValid = true;
			}
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			if( !empty( $_POST['user_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}
			if( $emailOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
				wp_send_json($out);
				exit;
			}
			if( $gaOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				wp_send_json($out);
				exit;
			}
			update_user_meta( $user_id, 'withdrawal_suspension_5_minute', 'disable' );
			$out = array( "error" => 0,'msg' => __('Disabled', CIP_TXTDOMAIN) );
			$current_user = wp_get_current_user();
			$logs = sprintf( __('Withdrawal suspension for a minutes after login disabled by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'profile', '','member', $logs, true );
		}else{
			$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
		}
	}
	wp_send_json($out);
	exit;
}
/* add_action('wp_ajax_disable_withdrawal_suspension_kyc_verification_act', 'disable_withdrawal_suspension_kyc_verification_act_callback');
function disable_withdrawal_suspension_kyc_verification_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong. Please try agin or contact admin.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_DisableWithdrawalSuspension_' ) && current_user_can( 'member' ) ){
		global $wpdb;
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$tableKycData = $wpdb->prefix.'kyc_data';
		$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
		$checkKycStatus = $wpdb->get_row("SELECT * FROM $tableKycData WHERE $whereEmail AND `status`='approved'");

		if( !empty( $_POST['kyc_dob'] ) ){
			$isDobValid = false;
			$isNumberValid = false;
			if( $checkKycStatus->account_type == 'business' ){
				if( $_POST['kyc_dob'] == $checkKycStatus->business_owner_dob ){
					$isDobValid = true;
				}
			}else{
				if( $_POST['kyc_dob'] == $checkKycStatus->dob ){
					$isDobValid = true;
				}
			}

			if( $checkKycStatus->account_type == 'business' ){
				if( $_POST['kyc_number'] == $checkKycStatus->business_registration_number ){
					$isNumberValid = true;
				}
			}else{
				if( $_POST['kyc_number'] == $checkKycStatus->document_number ){
					$isNumberValid = true;
				}
			}
			if( $isDobValid && $isNumberValid ){
				update_user_meta( $user_id, 'withdrawal_suspension_5_minute', 'disable' );
				$out = array( "error" => 0,'msg' => __('Disabled', CIP_TXTDOMAIN) );
				$current_user = wp_get_current_user();
				$logs = sprintf( __('Withdrawal suspension for a minutes after login disabled by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( $current_user->ID, 'profile', '','member', $logs, true );
			}else{
				$out = array( "error" => 1,'msg' => __('KYC/KYB data not verified.', CIP_TXTDOMAIN) );
				wp_send_json($out);
				exit;
			}
		}
	}
	wp_send_json($out);
	exit;
} */
add_action('admin_post_withdrawal_request_export_act','cip_withdrawal_request_export_act_callback');
function cip_withdrawal_request_export_act_callback(){
	if( wp_verify_nonce( $_POST['_micro'],'_CIP_WITHDRAWAL_REQUEST_EXPORT_CIP_' ) ){
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
		$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1");
		$exportFile = fopen('php://memory', 'w');
		$columnHeader = array( 'Withdrawal id', 'Email', 'CSR address', 'Withdrawal amount', 'Withdrawal fee', 'Received amount', 'Requested date' );
		fputcsv($exportFile, $columnHeader);
		foreach( $getWithdrawList as $getWithdrawal ){
			$requested_date = "";
			if( $getWithdrawal->requested_date ){
				$formattedRDate = DateTime::createFromFormat( 'Y-m-d H:i:s', $getWithdrawal->requested_date );
				if( $formattedRDate ){
					$requested_date = $formattedRDate->format('d-m-Y H:i:s');
				}
			}
			$rowData = array(
				$getWithdrawal->id,
				$getWithdrawal->email,
				$getWithdrawal->eth_address,
				number_format( $getWithdrawal->withdraw_amount, 2 ),
				number_format( $getWithdrawal->withdrawal_fee, 2),
				number_format( $getWithdrawal->received_amount, 2),
				$requested_date
			);
			fputcsv($exportFile, $rowData);
		}
		$current_user = wp_get_current_user();
		$logs = sprintf( __('CSR Withdrawal Pending Requests download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		fseek($exportFile, 0);
		$file_name = 'CSR_withdrawal_'.date_i18n('Y_m_d');
		header('content-type:application/csv;charset=UTF-8');
		header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
		fpassthru($exportFile);
		fclose($exportFile);
		exit;
	}
	echo "Opps! Something went wrong";
	exit;
}
add_action('wp_ajax_cip_wd_selection_storing_act', 'cip_wd_selection_storing_act_callback');
function cip_wd_selection_storing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$selectedAllOption = $_POST['selectedAllOption'];
		$thisId = $_POST['thisId'];
		$thisRowSelected = $_POST['thisRowSelected'];
		$sessionSelectionData = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		if( $selectedAllOption == 1 ){
			if( $thisRowSelected == 0 ){
				$sessionSelectionData[] = $thisId;
				$_SESSION['sessionSelectionData'] = array_unique( $sessionSelectionData );
			}else{
				$key = array_search($thisId, $sessionSelectionData, true);
				if ($key !== false) {
					unset($sessionSelectionData[$key]);
					$_SESSION['sessionSelectionData'] = array_unique( $sessionSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}else if( $selectedAllOption == 0 ){
			if( $thisRowSelected == 1 ){
				$sessionSelectionData[] = $thisId;
				$_SESSION['sessionSelectionData'] = array_unique( $sessionSelectionData );
			}else{
				$key = array_search($thisId, $sessionSelectionData, true);
				if ($key !== false) {
					unset($sessionSelectionData[$key]);
					$_SESSION['sessionSelectionData'] = array_unique( $sessionSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_cip_wd_request_selection_storing_act', 'cip_wd_request_selection_storing_act_callback');
function cip_wd_request_selection_storing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$selectedAllOption = $_POST['selectedAllOption'];
		$thisId = $_POST['thisId'];
		$thisRowSelected = $_POST['thisRowSelected'];
		$sessionSelectionData = ( isset( $_SESSION['sessionWdRequestSelectionData'] ) && !empty( $_SESSION['sessionWdRequestSelectionData'] ) ) ? $_SESSION['sessionWdRequestSelectionData'] : array();
		if( $selectedAllOption == 1 ){
			if( $thisRowSelected == 0 ){
				$sessionSelectionData[] = $thisId;
				$_SESSION['sessionWdRequestSelectionData'] = array_unique( $sessionSelectionData );
			}else{
				$key = array_search($thisId, $sessionSelectionData, true);
				if ($key !== false) {
					unset($sessionSelectionData[$key]);
					$_SESSION['sessionWdRequestSelectionData'] = array_unique( $sessionSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}else if( $selectedAllOption == 0 ){
			if( $thisRowSelected == 1 ){
				$sessionSelectionData[] = $thisId;
				$_SESSION['sessionWdRequestSelectionData'] = array_unique( $sessionSelectionData );
			}else{
				$key = array_search($thisId, $sessionSelectionData, true);
				if ($key !== false) {
					unset($sessionSelectionData[$key]);
					$_SESSION['sessionWdRequestSelectionData'] = array_unique( $sessionSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_cip_wd_selection_clearing_act', 'cip_wd_selection_clearing_act_callback');
function cip_wd_selection_clearing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$_SESSION['sessionSelectionData'] = array();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_cip_wd_request_selection_clearing_act', 'cip_wd_request_selection_clearing_act_callback');
function cip_wd_request_selection_clearing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$_SESSION['sessionWdRequestSelectionData'] = array();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
	}
	wp_send_json($out);
	exit;
}
add_action( 'template_redirect', 'support_agent_to_force_set2fa', 20 );
function support_agent_to_force_set2fa(){
	$current_user = wp_get_current_user();
	$user_roles = $current_user->roles;
	if( is_user_logged_in() ){
		if( \Elementor\Plugin::$instance->editor->is_edit_mode() ){

		}else{
			if ( ( in_array('supportagent', $user_roles) || in_array('supportmanager', $user_roles) || in_array('administrator', $user_roles) ) && !is_page(1330) ) {
				$user_id = $current_user->ID;
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$google_auth_key_login = get_user_meta( $user_id, 'google_auth_key_login', true );
				$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
				if( empty( $google_auth_key ) || $google_auth_key_login != 1 || $google_auth_key_walletdelivery != 1 ){
					$saProfilePage = get_permalink( 1330 );
					wp_safe_redirect( $saProfilePage );
					exit();
				}
			}
		}
	}

}
add_action( 'wp_ajax_cip_reset_sa_2faauth_act', 'cip_reset_sa_2faauth_act_callback' );
function cip_reset_sa_2faauth_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_XyResetSupportAgent2FaAuthyX_' ) && ( 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_SupportagenT_CL324') ), '', $decrypted_id_raw);
		$reset = false;
		$memberInfo = get_userdata($user_id);
		if( $user_id && in_array( "supportagent", $memberInfo->roles ) ){
			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() );

				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_walletdelivery' );
					$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(support agent) by %s at %s', 'corsair-login'),$memberInfo->user_email, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$reset = true;
					//logged-out this SA from other active session
					$sessions = WP_Session_Tokens::get_instance($user_id);
					$sessions->destroy_all();
				}
				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( get_email_send_toggle('2fa_enabled_disabled') == 1 ){
						$sent_mail = wp_mail( $memberInfo->user_email, $subject, $htmlContent );
					}

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

			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_sa_withdrawal_request_wizard_action', 'sa_withdrawal_request_wizard_action_callback' );
function sa_withdrawal_request_wizard_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.','corsair-login') );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPWithdrawalRequestWizardCIP_' ) && ( current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
		$tableWithdrawInProcess = $wpdb->prefix.'withdraw_data_inprocess';
		$tableWithdrawComplete = $wpdb->prefix.'withdraw_data_completed';
		$tableDeliveryTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
		$tableWithdrawalRequestsCsv = $wpdb->prefix.'withdrawal_requests_csv';
		$currentUserData = wp_get_current_user();
		$user_id = $currentUserData->ID;
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		// $ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_login == 1 ) ? 1 : 0;
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $corsair_2fa_ga != 'yes' || $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.','corsair-login') );
			echo wp_json_encode( $out );
			exit;
		}

		$withdrawal_request_wizard_process_user = get_option('withdrawal_request_wizard_process_user');

		if( !empty( $withdrawal_request_wizard_process_user ) && $withdrawal_request_wizard_process_user != $currentUserData->ID ){
			$out = array( "error" => 1,'msg' => __('Withdrawal request process already started by other user','corsair-login') );
			echo wp_json_encode( $out );
			exit;
		}
		if( isset( $_POST['isExportProcess'] ) && $_POST['isExportProcess'] == 1 ){
			$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
			/* $sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionWdRequestSelectionData'] ) && !empty( $_SESSION['sessionWdRequestSelectionData'] ) ) ? $_SESSION['sessionWdRequestSelectionData'] : array();
			$sessionSelectionData = array();
			if( !empty( $sessionSelectionDataEncrypt ) ){
				foreach( $sessionSelectionDataEncrypt as $encryptId ){
					$decryptedIdRaw = base64_decode( $encryptId );
					$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
					$sessionSelectionData[] = $decryptedUserId;
				}
			} */
			$withdrawRequestIdsEncrypt = ( isset( $_POST['withdrawRequestIds'] ) && !empty( $_POST['withdrawRequestIds'] ) ) ? $_POST['withdrawRequestIds'] : array();
			$withdrawRequestIdsData = array();
			if( !empty( $withdrawRequestIdsEncrypt ) ){
				foreach( $withdrawRequestIdsEncrypt as $encryptId ){
					$decryptedIdRaw = base64_decode( $encryptId );
					$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
					$withdrawRequestIdsData[] = $decryptedUserId;
				}
			}
			$current_user = wp_get_current_user();
			$user_id = $current_user->ID;
			/* $sessionDataQry = "";
			if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
				$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
			}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
				$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
			} */
			$sessionDataQry = "";
			$sessionDataQry = ' AND `id` IN ('. implode(',', $withdrawRequestIdsData) .')';
			$filter_qry = " AND ( `withdrawal_process_status` != 'Under review' OR `withdrawal_process_status` IS NULL )";

			$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
			$filterByUsername = "";
			$filterByValueUsername = "";
			if( !empty( $filterByConditionsUsername ) ){
				$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
				if( $filterByUsername == 'is_exactly_simple' ){
					$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
				}else{
					$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
				}
			}
			$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );

			if( $filterByUsername != 'none' ){
				$filters['username'] = $filterByValueUsername;
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 AND ( `withdrawal_process_status` != 'Under review' OR `withdrawal_process_status` IS NULL ) $sessionDataQry");
			$isNumericColumn = array('withdraw_amount', 'withdrawal_fee', 'received_amount');
			if( !empty( $filters ) ){

				foreach( $filters as $filterKey => $filterData ){
					if( $filterKey == 'withdrawal_id' ){
						$filter_qry .= " AND `withdrawal_id`='".$filterData."'";
					}else if( $filterKey == 'requested_date' ){

						$dateObject = explode(" - ",$filterData);
						$fromDate = "";
						$toDate = "";
						if( isset( $dateObject[0] ) && isset( $dateObject[1] ) ){
							$fromDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[0]);
							if( $fromDateObj ){
								$fromDate = $fromDateObj->format('Y-m-d');
							}
							$toDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[1]);
							if( $toDateObj ){
								$toDate = $toDateObj->format('Y-m-d');
							}
							if( $fromDate && $toDate ){
								$filter_qry .= " AND (date(`requested_date`) BETWEEN '$fromDate' AND '$toDate')";
							}
						}

					}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
						if( str_contains($filterData, '-') ){ //between
							$filterDataMinMax = explode('-', $filterData);
							$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
						}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
							$filter_qry .= " AND `$filterKey` $filterData";
						}else{
							$filter_qry .= " AND `$filterKey` = " . $filterData . "";
						}
					}else if( $filterKey == 'username' ){
						if( $filterByUsername != 'none' ){
							if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
								$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
							}
						}
					}else if( $filterKey == 'withdrawal_process_status' ){
						if( $filterData == 'Pending' ){
							$filter_qry .= " AND ( `$filterKey` = '" . $filterData . "' OR `$filterKey` IS NULL )";
						}else{
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}
					}else if( $filterKey == 'token' ){
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					}else{
						$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
					}
				}
				$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
			}
			$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");

			$tokenTypeArray = array();
			$tokenTypeText = "";
			if( $getWithdrawList ){
				foreach( $getWithdrawList as $getWithdrawListOne ){
					$tokenTypeArray[ strtoupper( $getWithdrawListOne->token ) ] = strtoupper( $getWithdrawListOne->token );
					$tokenTypeText = strtoupper( $getWithdrawListOne->token );
				}
			}

			if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
				$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}


			if( !$getWithdrawList ){
				$out = array( "error" => 1,'msg' => sprintf(  __('No %s available for delivery with current selection.', CIP_TXTDOMAIN), $tokenTypeText ) );
				echo wp_json_encode( $out );
				exit;
			}
			$exportFile = fopen('php://memory', 'w');
			$columnHeader = array( 'username', 'eth_address', 'amount_due', 'email', 'date' );
			fputcsv($exportFile, $columnHeader);
			foreach( $getWithdrawList as $getWithdrawal ){
				$requested_date = "";
				if( $getWithdrawal->requested_date ){
					$formattedRDate = DateTime::createFromFormat( 'Y-m-d H:i:s', $getWithdrawal->requested_date );
					if( $formattedRDate ){
						$requested_date = $formattedRDate->format('d/m/Y');
					}
				}
				$rowData = array(
					$getWithdrawal->username,
					$getWithdrawal->eth_address,
					number_format( $getWithdrawal->received_amount, 2, '.', ''),
					$getWithdrawal->email,
					$requested_date
				);
				fputcsv($exportFile, $rowData);
			}
			fseek($exportFile, 0);
			$file_name = 'CSR_withdrawal_'.date_i18n('Y_m_d_h_i').'_'.$tokenTypeText;
			$filedata = stream_get_contents($exportFile);

			$fileid = uniqidReal();
			update_option( 'withdrawal_request_wizard_export_fileid', $fileid );
			$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT(`eth_address`)) FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
			$totalWithdrawalsAmount = 0;
			$totalWithdrawals = 0;
			$totalWithdrawalsAmountFees = 0;
			$totalAmountFee = 0;

			$receivedAmountData = $wpdb->get_row("SELECT COALESCE(SUM(`received_amount`),0) as `received_amount` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
			$receivedAmountWithFeeData = $wpdb->get_row("SELECT COALESCE(SUM(`withdraw_amount`),0) as `withdraw_amount` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
			$AmountFeeData = $wpdb->get_row("SELECT COALESCE(SUM(`withdrawal_fee`),0) as `withdrawal_fee` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
			$withdrawalData = $wpdb->get_row("SELECT COUNT(*) as `totalCount` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");

			if( $receivedAmountData ){
				$totalWithdrawalsAmount = $receivedAmountData->received_amount;
			}
			if( $receivedAmountWithFeeData ){
				$totalWithdrawalsAmountFees = $receivedAmountWithFeeData->withdraw_amount;
			}
			if( $AmountFeeData ){
				$totalAmountFee = $AmountFeeData->withdrawal_fee;
			}
			if( $withdrawalData ){
				$totalWithdrawals = $withdrawalData->totalCount;
			}
			$csvData = array(
				'fileid'						=>	$fileid,
				'filename'						=>	$file_name,
				'filedata'						=>	$filedata,
				'_date'							=>	date_i18n('Y-m-d H:i:s'),
				'unique_address'				=>	$unique_addresses,
				'total_withdrawals'				=>	$totalWithdrawals,
				'total_withdrawals_amount'		=>	$totalWithdrawalsAmount,
				'total_withdrawals_amount_fees'	=>	$totalWithdrawalsAmountFees,
				'total_fee'						=>	$totalAmountFee,
				'status'						=>	0,
				'last_update'					=>	date_i18n('Y-m-d H:i:s'),
				'token'							=> 	$tokenTypeText
			);
			$insertCsvFile = $wpdb->insert( $tableWithdrawalRequestsCsv, $csvData );
			fpassthru($exportFile);
			fclose($exportFile);
			if( $insertCsvFile ){
				update_option( 'withdrawal_request_wizard_process_user', $currentUserData->ID );
				update_option( 'withdrawal_request_wizard_process_current_step', 2 );
				$logs = sprintf( __('Withdrawal request export (%s rows) by %s at %s', 'corsair-login'), count( $getWithdrawList ), $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
				$exportFileid = $fileid;
				$download_link = "";
				if( !empty( $exportFileid ) ){
					$result = $wpdb->get_row("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `fileid`='".$exportFileid."'");
					if( $result ){
						$encryptId = base64_encode( $result->fileid . md5('CIPWithdrawalRequestCSV'));
						$wizardExportUrl = add_query_arg( array(
							'action'	=> 'withdrawal_request_csv_download_act',
							'_micro'	=> wp_create_nonce('_CIP_WITHDRAWAL_REQUEST_DOWNLOAD_CSV_CIP_'),
							'file'		=> $encryptId,
						), admin_url('admin-post.php') );
						$download_link = '<a href="'.$wizardExportUrl.'">'.__('Download', CIP_TXTDOMAIN).'</a>';
					}
				}
				//step to move in process table
				$rowsMoved = 0;
				foreach( $getWithdrawList as $getWithdrawal ){

					$insertData = array(
						'user_id'					=>	$getWithdrawal->user_id,
						'withdrawal_id'				=>	$getWithdrawal->withdrawal_id,
						'username'					=>	$getWithdrawal->username,
						'first_name'				=>	$getWithdrawal->first_name,
						'last_name'					=>	$getWithdrawal->last_name,
						'email'						=>	$getWithdrawal->email,
						'user_star'					=>	$getWithdrawal->user_star,
						'eth_address'				=>	$getWithdrawal->eth_address,
						'withdraw_amount'			=>	$getWithdrawal->withdraw_amount,
						'min_withdraw_amount'		=>	$getWithdrawal->min_withdraw_amount,
						'withdrawal_fee'			=>	$getWithdrawal->withdrawal_fee,
						'received_amount'			=>	$getWithdrawal->received_amount,
						'status'					=>	1,
						'requested_date'			=>	$getWithdrawal->requested_date,
						'processed_date'			=>	date_i18n('Y-m-d H:i:s'),
						'amount_to_distribute'		=>	$getWithdrawal->received_amount,
						'withdrawal_process_status'	=>	$getWithdrawal->withdrawal_process_status,
						'token'						=>	$getWithdrawal->token,
					);
					$insertInProcess = $wpdb->insert( $tableWithdrawInProcess, $insertData );
					if( $insertInProcess ){
						$wpdb->delete( $tableWithdraw, [ 'id' => $getWithdrawal->id ] );

						$wpdb->update( $tableDeliveryTransactionHistory, ['status' => 1], [ 'txn_id' => $getWithdrawal->withdrawal_id ] );

						$rowsMoved++;
						$logs = sprintf( __('Withdrawal request moved from pending to in process withdrawal_id: %s, email: %s, eth_address: %s, withdraw_amount: %s, received_amount: %s, requested_date: %s by %s at %s', 'corsair-login'), $getWithdrawal->withdrawal_id, $getWithdrawal->email, $getWithdrawal->eth_address, $getWithdrawal->withdraw_amount, $getWithdrawal->received_amount, $getWithdrawal->requested_date, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
					}
				}
				$logs = sprintf( __('Withdrawal request moved from pending to in process (%s rows) by %s at %s', 'corsair-login'), $rowsMoved, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
				$out = array( "error" => 0,'msg' => __( 'Success', CIP_TXTDOMAIN ),'responseHtml' => sprintf( __('%s rows in process','corsair-login'), $rowsMoved ), 'download_link' => $download_link );
				// $out = array( "error" => 0,'msg' => __('Success','corsair-login'), 'download_link' => $download_link );
			}

			/* header('content-type:application/csv;charset=UTF-8');
			header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
			exit; */
		}else if( isset( $_POST['isdistribution_takes_place'] ) && $_POST['isdistribution_takes_place'] == 1 ){
			/* $getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1");
			$rowsMoved = 0;
			if( $getWithdrawList ){

				update_option( 'withdrawal_request_wizard_process_current_step', 3 );
				foreach( $getWithdrawList as $getWithdrawal ){

					$insertData = array(
						'user_id'				=>	$getWithdrawal->user_id,
						'withdrawal_id'			=>	$getWithdrawal->withdrawal_id,
						'username'				=>	$getWithdrawal->username,
						'email'					=>	$getWithdrawal->email,
						'eth_address'			=>	$getWithdrawal->eth_address,
						'withdraw_amount'		=>	$getWithdrawal->withdraw_amount,
						'min_withdraw_amount'	=>	$getWithdrawal->min_withdraw_amount,
						'withdrawal_fee'		=>	$getWithdrawal->withdrawal_fee,
						'received_amount'		=>	$getWithdrawal->received_amount,
						'status'				=>	1,
						'requested_date'		=>	$getWithdrawal->requested_date,
						'processed_date'		=>	date_i18n('Y-m-d H:i:s'),
						'amount_to_distribute'	=>	$getWithdrawal->received_amount,
					);
					$insertInProcess = $wpdb->insert( $tableWithdrawInProcess, $insertData );
					if( $insertInProcess ){
						$wpdb->delete( $tableWithdraw, [ 'id' => $getWithdrawal->id ] );

						$wpdb->update( $tableDeliveryTransactionHistory, ['status' => 1], [ 'txn_id' => $getWithdrawal->withdrawal_id ] );

						$rowsMoved++;
						$logs = sprintf( __('Withdrawal request moved pending to in process withdrawal_id: %s, email: %s, eth_address: %s, withdraw_amount: %s, received_amount: %s, requested_date: %s by %s at %s', 'corsair-login'), $getWithdrawal->withdrawal_id, $getWithdrawal->email, $getWithdrawal->eth_address, $getWithdrawal->withdraw_amount, $getWithdrawal->received_amount, $getWithdrawal->requested_date, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
					}
				}
				$logs = sprintf( __('Withdrawal request moved pending to in process (%s rows) by %s at %s', 'corsair-login'), $rowsMoved, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
				$out = array( "error" => 0,'msg' => __( 'Success', CIP_TXTDOMAIN ),'responseHtml' => sprintf( __('%s rows in process','corsair-login'), $rowsMoved ) );
			} */
		}else if( isset( $_POST['isCompleteProcess'] ) && $_POST['isCompleteProcess'] == 1 ){
			$gaOTPValid = false;
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			if( !empty( $_POST['user_complete_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_complete_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}

			if( empty( $_POST['sa_txnhash'] ) ){
				$out = array( "error" => 1,'msg' => __('Please enter transaction hash.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			if( $gaOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			if( $gaOTPValid === true ){

				$getWithdrawProcessList = $wpdb->get_results("SELECT * FROM $tableWithdrawInProcess WHERE 1 $filter_qry");
				$rowsMoved = 0;
				$eth_address_arr = array();
				$totalWithdrawalsAmount = 0;
				$totalWithdrawals = 0;

				$exportFileId = get_option('withdrawal_request_wizard_export_fileid');
				$withdrawalBatchId = get_option('withdrawal_batch_id');
				if( !empty( $withdrawalBatchId ) ){
					$withdrawalBatchId = $withdrawalBatchId + 1;
				}else{
					$withdrawalBatchId = 1;
				}
				$withdrawal_batch_id = $withdrawalBatchId;
				$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 = __('Withdrawal complete', CIP_TXTDOMAIN);
				$tableCipNotice = $wpdb->prefix.'cip_notice';

				if( $getWithdrawProcessList ){
					foreach( $getWithdrawProcessList as $getWithdrawal ){

						$insertData = array(
							'user_id'					=>	$getWithdrawal->user_id,
							'withdrawal_id'				=>	$getWithdrawal->withdrawal_id,
							'username'					=>	$getWithdrawal->username,
							'first_name'				=>	$getWithdrawal->first_name,
							'last_name'					=>	$getWithdrawal->last_name,
							'email'						=>	$getWithdrawal->email,
							'user_star'					=>	$getWithdrawal->user_star,
							'eth_address'				=>	$getWithdrawal->eth_address,
							'withdraw_amount'			=>	$getWithdrawal->withdraw_amount,
							'min_withdraw_amount'		=>	$getWithdrawal->min_withdraw_amount,
							'withdrawal_fee'			=>	$getWithdrawal->withdrawal_fee,
							'received_amount'			=>	$getWithdrawal->received_amount,
							'status'					=>	2,
							'requested_date'			=>	$getWithdrawal->requested_date,
							'processed_date'			=>	date_i18n('Y-m-d H:i:s'),
							'amount_to_distribute'		=>	$getWithdrawal->received_amount,
							'fileid'					=>	$exportFileId,
							'transhash'					=>	$_POST['sa_txnhash'],
							'withdrawal_batch_id'		=>	$withdrawal_batch_id,
							'withdrawal_process_status'	=>	$getWithdrawal->withdrawal_process_status,
							'token'						=>	$getWithdrawal->token,
						);
						$insertComplete = $wpdb->insert( $tableWithdrawComplete, $insertData );
						if( $insertComplete ){

							$wpdb->delete( $tableWithdrawInProcess, [ 'id' => $getWithdrawal->id ] );

							$wpdb->update( $tableDeliveryTransactionHistory, ['status' => 2, 'transhash' => $_POST['sa_txnhash']], [ 'txn_id' => $getWithdrawal->withdrawal_id ] );

							$rowsMoved++;

							$eth_address_arr[] = $getWithdrawal->eth_address;
							$totalWithdrawalsAmount += $getWithdrawal->received_amount;

							$logs = sprintf( __('Withdrawal request moved from in process to complete withdrawal_id: %s, email: %s, eth_address: %s, withdraw_amount: %s, received_amount: %s, requested_date: %s by %s at %s', 'corsair-login'), $getWithdrawal->withdrawal_id, $getWithdrawal->email, $getWithdrawal->eth_address, $getWithdrawal->withdraw_amount, $getWithdrawal->received_amount, $getWithdrawal->requested_date, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
							//notice of withdrawal request
							$notificationMessageText = sprintf( __('%s '. $tokenTypeText .' has been successfully withdrawn from your wallet.', CIP_TXTDOMAIN), number_format( $getWithdrawal->received_amount, 2 ) );
							$noticeData = array(
								"email"		=>	$getWithdrawal->email,
								"username"	=>	'',
								"notice"	=>	$notificationMessageText,
								"status"	=>	1,
								"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
							);
							$wpdb->insert( $tableCipNotice, $noticeData );
							$messageText = sprintf( __('<p class="text-left text-size-18">%s CSR has been successfully withdrawn from your wallet to your blockchain address: %s.</p><p class="text-left text-size-18"><b>Transaction Reference: %s</b></p><p class="text-left text-size-18"><b>Transaction Hash: %s</b></p>', CIP_TXTDOMAIN), number_format( $getWithdrawal->received_amount, 2), $getWithdrawal->eth_address, $getWithdrawal->withdrawal_id, $_POST['sa_txnhash'] );
							$message = sprintf( __('<h2>Dear Member,</h2><h3>%s', CIP_TXTDOMAIN), $messageText );
							$htmlContent = mailTemplateHtmlRender( $message );
							if( get_email_send_toggle('withdrawal_complete') == 1 ){
								wp_mail( $getWithdrawal->email, $subject, $htmlContent );
							}

						}
						$totalWithdrawals = $rowsMoved;
					}

					if( !empty( $exportFileId ) ){
						$updateFileData = $wpdb->update( $tableWithdrawalRequestsCsv, ['status' => 1, 'last_update' => date_i18n('Y-m-d H:i:s'), 'transhash' =>	$_POST['sa_txnhash'], 'withdrawal_batch_id'	=>	$withdrawal_batch_id], ['fileid' => $exportFileId] );
					}

					delete_option( 'withdrawal_request_wizard_process_user' );
					delete_option( 'withdrawal_request_wizard_process_current_step' );
					delete_option( 'withdrawal_request_wizard_export_fileid' );

					// $logs = sprintf( __('Withdrawal request with withdrawal report ID %s moved from in process to complete (%s rows) by %s at %s', 'corsair-login'), $exportFileId, $rowsMoved, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					$logs = sprintf( __('Withdrawal request with withdrawal batch id %s moved from in process to complete (%s rows) by %s at %s', 'corsair-login'), $withdrawal_batch_id, $rowsMoved, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );
					if( get_sms_send_toggle('batch_distribution') == 1 ){
						$content = sprintf(__('Batch distribution of %s '.$tokenTypeText.' performed by %s', CIP_TXTDOMAIN), number_format( $totalWithdrawalsAmount ), $currentUserData->user_email );
						brevo_sms_alert_send( $content );
					}
					$responseHtml = "";
					ob_start();
					?>
					<p><?php echo sprintf( __('Total withdrawals : %s', CIP_TXTDOMAIN ), $totalWithdrawals ); ?></p>
					<p><?php echo sprintf( __('Total '.$tokenTypeText.' withdrawal amount : %s '.$tokenTypeText.'', CIP_TXTDOMAIN ), number_format( $totalWithdrawalsAmount, 2 ) ); ?></p>
					<p><?php echo sprintf( __('Unique '.$tokenTypeText.' addresses : %s', CIP_TXTDOMAIN ), count( array_unique( $eth_address_arr ) ) ); ?></p>
					<?php
					$responseHtml .= ob_get_clean();

					$out = array( "error" => 0,'msg' => __( 'Success', CIP_TXTDOMAIN ),'responseHtml' => $responseHtml );
					update_option( 'withdrawal_batch_id', $withdrawalBatchId );
				}
			}
		}else if( isset( $_POST['isCancelProcess'] ) && $_POST['isCancelProcess'] == 1 ){
			$gaOTPValid = false;
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			if( isset( $_POST['isCancelProcessCheck2fa'] ) && $_POST['isCancelProcessCheck2fa'] == 1 ){
				$authCode = "";
				if( isset( $_POST['stage'] ) && $_POST['stage'] == 'complete' ){
					if( !empty( $_POST['user_complete_ga_otp'] ) ){
						$google2fa = new \PragmaRX\Google2FA\Google2FA();
						if( $google2fa->verifyKey($google_auth_key, $_POST['user_complete_ga_otp'], 0) ){
							$gaOTPValid = true;
							$authCode = $_POST['user_complete_ga_otp'];
						}
					}
				}else{
					if( !empty( $_POST['user_ga_otp'] ) ){
						$google2fa = new \PragmaRX\Google2FA\Google2FA();
						if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
							$gaOTPValid = true;
							$authCode = $_POST['user_ga_otp'];
						}
					}
				}
				if( $gaOTPValid === false ){
					$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}else if( $gaOTPValid === true ){
					$_SESSION['cancelWRAuthCode'] = $authCode;
					$out = array( "error" => 0,'msg' => __( 'success', CIP_TXTDOMAIN ), 'authCode' => $authCode );
				}
			}else if( isset( $_POST['isCancelProcessCheck2faValue'] ) && !empty( $_POST['isCancelProcessCheck2faValue'] ) ){
				$gaOTPValid = false;
				$authCode = "";
				if( isset( $_POST['stage'] ) && $_POST['stage'] == 'complete' ){
					$authCode = $_POST['user_complete_ga_otp'];
				}else{
					$authCode = $_POST['user_ga_otp'];
				}
				if( !empty( $_POST['isCancelProcessCheck2faValue'] ) && $_SESSION['cancelWRAuthCode'] == $_POST['isCancelProcessCheck2faValue'] && $authCode == $_SESSION['cancelWRAuthCode'] ){
					$gaOTPValid = true;
				}
				if( $gaOTPValid === true ){
					$getWithdrawProcessList = $wpdb->get_results("SELECT * FROM $tableWithdrawInProcess WHERE 1");
					$rowsMoved = 0;
					if( $getWithdrawProcessList ){
						foreach( $getWithdrawProcessList as $getWithdrawal ){

							$insertData = array(
								'user_id'					=>	$getWithdrawal->user_id,
								'withdrawal_id'				=>	$getWithdrawal->withdrawal_id,
								'username'					=>	$getWithdrawal->username,
								'first_name'				=>	$getWithdrawal->first_name,
								'last_name'					=>	$getWithdrawal->last_name,
								'email'						=>	$getWithdrawal->email,
								'user_star'					=>	$getWithdrawal->user_star,
								'eth_address'				=>	$getWithdrawal->eth_address,
								'withdraw_amount'			=>	$getWithdrawal->withdraw_amount,
								'min_withdraw_amount'		=>	$getWithdrawal->min_withdraw_amount,
								'withdrawal_fee'			=>	$getWithdrawal->withdrawal_fee,
								'received_amount'			=>	$getWithdrawal->received_amount,
								'status'					=>	0,
								'requested_date'			=>	$getWithdrawal->requested_date,
								'processed_date'			=>	'',
								'amount_to_distribute'		=>	$getWithdrawal->received_amount,
								'withdrawal_process_status'	=>	$getWithdrawal->withdrawal_process_status,
								'token'						=>	$getWithdrawal->token,
							);
							$insertPending = $wpdb->insert( $tableWithdraw, $insertData );
							if( $insertPending ){
								$wpdb->delete( $tableWithdrawInProcess, [ 'id' => $getWithdrawal->id ] );

								$wpdb->update( $tableDeliveryTransactionHistory, ['status' => 0], [ 'txn_id' => $getWithdrawal->withdrawal_id ] );

								$rowsMoved++;

								$logs = sprintf( __('Withdrawal request moved from cancelled, moved to pending withdrawal_id: %s, email: %s, eth_address: %s, withdraw_amount: %s, received_amount: %s, requested_date: %s by %s at %s', 'corsair-login'), $getWithdrawal->withdrawal_id, $getWithdrawal->email, $getWithdrawal->eth_address, $getWithdrawal->withdraw_amount, $getWithdrawal->received_amount, $getWithdrawal->requested_date, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );

							}
						}
						unset( $_SESSION['cancelWRAuthCode'] );
						$_SESSION['cancelWRAuthCode'] = "";

						delete_option( 'withdrawal_request_wizard_process_user' );
						delete_option( 'withdrawal_request_wizard_process_current_step' );
						delete_option( 'withdrawal_request_wizard_export_fileid' );

						$logs = sprintf( __('Withdrawal request cancelled (%s rows) by %s at %s', 'corsair-login'), $rowsMoved, $currentUserData->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'sa', '','sa', $logs, true );

						$out = array( "error" => 0,'msg' => __( 'Withdrawal request cancelled', CIP_TXTDOMAIN ) );
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
		}else if( isset( $_POST['isDownloadProcess'] ) && $_POST['isDownloadProcess'] == 1 ){

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

				$exportFileId = get_option('withdrawal_request_wizard_export_fileid');
				if( $exportFileId ){
					$result = $wpdb->get_row("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `fileid`='".$exportFileId."'");
					$updateDownloadStatus = $wpdb->update( $tableWithdrawalRequestsCsv, ['downloadStatus' => 1], ['fileid' => $exportFileId] );
					$encryptId = base64_encode( $result->fileid . md5('CIPWithdrawalRequestCSV'));
					$_SESSION['tempExpoDownFile'] = $_POST['user_ga_otp'];
					$wizardExportUrl = add_query_arg( array(
						'action'	=> 'withdrawal_request_csv_download_act',
						'_micro'	=> wp_create_nonce('_CIP_WITHDRAWAL_REQUEST_DOWNLOAD_CSV_CIP_'),
						'file'		=> $encryptId,
						'_microId'	=> $_POST['user_ga_otp'],
					), admin_url('admin-post.php') );
					$download_link = '<a href="'.$wizardExportUrl.'" download target="_blank">'.__('Download', CIP_TXTDOMAIN).'</a>';
					$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'download_link' => $download_link );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('admin_post_withdrawal_request_csv_download_act','cip_withdrawal_request_csv_download_act_callback');
function cip_withdrawal_request_csv_download_act_callback(){
	if( wp_verify_nonce( $_REQUEST['_micro'],'_CIP_WITHDRAWAL_REQUEST_DOWNLOAD_CSV_CIP_' ) ){
		global $wpdb;
		$tableWithdrawalRequestsCsv = $wpdb->prefix.'withdrawal_requests_csv';
		$decrypted_id_raw = base64_decode( $_REQUEST['file'] );
		$fileid = preg_replace(sprintf('/%s/', md5('CIPWithdrawalRequestCSV') ), '', $decrypted_id_raw);
		$result = $wpdb->get_row("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `fileid`='".$fileid."'");
		if( $result && ( isset( $_REQUEST['_microId'] ) && $_REQUEST['_microId'] == $_SESSION['tempExpoDownFile'] ) ){
			unset( $_SESSION['tempExpoDownFile'] );
			$_SESSION['tempExpoDownFile'] = "";
			$current_user = wp_get_current_user();
			$logs = sprintf( __('CSR Withdrawal Requests download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
			$file_name = $result->filename;
			$csvData = $result->filedata;
			header('content-type:application/csv;charset=UTF-8');
			header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
			echo $csvData;
			exit;
		}

	}
	echo "Opps! Something went wrong";
	exit;
}
add_action('admin_post_completed_withdrawal_request_csv_download_act','cip_completed_withdrawal_request_csv_download_act_callback');
function cip_completed_withdrawal_request_csv_download_act_callback(){
	if( wp_verify_nonce( $_REQUEST['_micro'],'_CIP_COMPLETED_WITHDRAWAL_REQUEST_DOWNLOAD_CSV_CIP_' ) ){
		global $wpdb;
		$tableWithdrawalRequestsCsv = $wpdb->prefix.'withdrawal_requests_csv';
		$decrypted_id_raw = base64_decode( $_REQUEST['file'] );
		$fileid = preg_replace(sprintf('/%s/', md5('CIPWithdrawalRequestCSV') ), '', $decrypted_id_raw);
		$result = $wpdb->get_row("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `fileid`='".$fileid."'");
		if( $result ){
			$current_user = wp_get_current_user();
			$logs = sprintf( __('CSR Withdrawal Completed download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
			create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
			$file_name = $result->filename;
			$csvData = $result->filedata;
			header('content-type:application/csv;charset=UTF-8');
			header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
			echo $csvData;
			exit;
		}

	}
	echo "Opps! Something went wrong";
	exit;
}
add_action('wp_ajax_cip_sacsr_selection_storing_act', 'cip_sacsr_selection_storing_act_callback');
function cip_sacsr_selection_storing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$selectedAllOption = $_POST['selectedAllOption'];
		$thisId = $_POST['thisId'];
		$thisRowSelected = $_POST['thisRowSelected'];
		$sessionSaCsrSelectionData = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		if( $selectedAllOption == 1 ){
			if( $thisRowSelected == 0 ){
				$sessionSaCsrSelectionData[] = $thisId;
				$_SESSION['sessionSaCsrSelectionData'] = array_unique( $sessionSaCsrSelectionData );
			}else{
				$key = array_search($thisId, $sessionSaCsrSelectionData, true);
				if ($key !== false) {
					unset($sessionSaCsrSelectionData[$key]);
					$_SESSION['sessionSaCsrSelectionData'] = array_unique( $sessionSaCsrSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}else if( $selectedAllOption == 0 ){
			if( $thisRowSelected == 1 ){
				$sessionSaCsrSelectionData[] = $thisId;
				$_SESSION['sessionSaCsrSelectionData'] = array_unique( $sessionSaCsrSelectionData );
			}else{
				$key = array_search($thisId, $sessionSaCsrSelectionData, true);
				if ($key !== false) {
					unset($sessionSaCsrSelectionData[$key]);
					$_SESSION['sessionSaCsrSelectionData'] = array_unique( $sessionSaCsrSelectionData );
				}
			}
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
		}
	}
	wp_send_json($out);
	exit;
}
add_action('wp_ajax_cip_sacsr_selection_clearing_act', 'cip_sacsr_selection_clearing_act_callback');
function cip_sacsr_selection_clearing_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		$_SESSION['sessionSaCsrSelectionData'] = array();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN) );
	}
	wp_send_json($out);
	exit;
}
add_action( 'wp_ajax_editCheckingCsrProcess', 'editCheckingCsrProcess_callback' );
function editCheckingCsrProcess_callback(){
	global $wpdb;
	$tableSimpleNotes = $wpdb->prefix.'simple_notes';
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyEditCheckingProcessCsryX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}
		$sessionSaCsrSelectionDataEncrypt = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		$sessionSaCsrSelectionData = array();
		if( !empty( $sessionSaCsrSelectionDataEncrypt ) ){
			foreach( $sessionSaCsrSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_SASELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSaCsrSelectionData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		/* $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('You must enable Google Autheticator 2FA',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$filter_qry = "";
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		if( $filterBy != 'none' ){
			$filters['notes_external'] = trim( $filterByValue );
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $sessionDataQry");
		$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
		$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else if( $filterKey == 'username' ){
					$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
				}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
					if( str_contains($filterData, ' - ') ){
						$filterDataMinMax = explode(' - ', $filterData);
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
					}else{
						$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
					}
				}else if( $filterKey == 'notes_external' ){
					if( $filterBy != 'none' ){
						if( $filterBy == 'is_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
						}else if( $filterBy == 'is_not_empty' ){
							$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
						}else if( $filterBy == 'contains_text' ){
							$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'does_not_contains_text' ){
							$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
						}else if( $filterBy == 'starts_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
						}else if( $filterBy == 'ends_with' ){
							$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
						}else if( $filterBy == 'is_exactly' ){
							$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
						}
					}
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
		$elementNoteMaxCount = false;
		$notesArray = array();
		$elementNotesArray = array();
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember){
				$rowNotes = explode("|",$getCurrentMember->notes_external);
				if( !empty( $rowNotes ) ){
					foreach( $rowNotes as $rowNote){

						$trimRowNote = trim( $rowNote );
						if( !empty( $trimRowNote ) ){
							$notesArray[] = $trimRowNote;
						}
						//Element Notes
						if( !empty( $trimRowNote ) ){
							$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
							if( $isNoteElement ){
								$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
								$rowNotesElement = explode(" ; ",$notesResult);
								if( !empty( $rowNotesElement ) ){
									if( count( $rowNotesElement ) >= 5 ){
										$elementNoteMaxCount = true;
									}
									foreach( $rowNotesElement as $rowNotesElem ){
										$elementNotesArray[] = $rowNotesElem;
									}
								}
							}
						}
					}
				}
			}
		}
		if( $total_items <= 0 ){
			$out = array( "error" => 1,'msg' => __('No records to update.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$getSimpleNotes = $wpdb->get_results("SELECT * FROM $tableSimpleNotes WHERE 1 AND `status`=1");
		$html = "";
		ob_start();
		?>
		<form name="csr_edit_notes_frm" id="csr_edit_notes_frm">
			<div class="csr_delivery_summary_modal">
				<div class="d-flex d-flex justify-content-between" style="column-gap:30px;">
					<div>
						<h6 class="mb-1"><?php _e('Edit Summary', CIP_TXTDOMAIN ); ?></h6>
						<p class="text-left mb-1"> <?php _e('Rows to edit: ', CIP_TXTDOMAIN ); ?><span><?php echo number_format( $total_items ); ?></span> </p>
					</div>
					<div>
						<select name="element_type" id="element_type" class="form-control">
							<option value="simple"><?php _e('Simple', CIP_TXTDOMAIN); ?></option>
							<option value="notes"><?php _e('Notes', CIP_TXTDOMAIN); ?></option>
							<option value="complex"><?php _e('Complex', CIP_TXTDOMAIN); ?></option>
						</select>
					</div>
				</div>
			</div>
			<input type="hidden" name="action" value="csrEditNotesAction" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyCSREditNotesSimpleCSRXy_') ?>" />
			<hr class="mt-1 mb-1">
			<div class="pb-3 simpleElement">
				<?php if( $getSimpleNotes ){ ?>
					<div class="form-group">
						<input type="text" name="checklist_search" id="checklist_search" class="form-control" placeholder="<?php _e('Search', CIP_TXTDOMAIN); ?>" onkeyup="Searchcities(this,'#notesname');" />
					</div>
					<div class="notesname" id="notesname">
					<?php
					$finalNotesCountArr = array_count_values( $notesArray );
					foreach( $getSimpleNotes as $getSimpleNote ){
						$checked = "";
						$disabled = "";
						if( isset( $finalNotesCountArr[$getSimpleNote->notes] ) && $finalNotesCountArr[$getSimpleNote->notes] == $total_items ){
							$checked = "checked";
						}else if( isset( $finalNotesCountArr[$getSimpleNote->notes] ) && $finalNotesCountArr[$getSimpleNote->notes] != $total_items ){
							$disabled = "disabled";
							$checked = "checked";
						}
					?>
					<div class="custom-control custom-checkbox mb-1">
						<?php if( !empty( $checked ) && !empty( $disabled ) ){ ?>
							<input type="checkbox" name="simple_notes_disabled[]" class="custom-control-input <?php echo $disabled; ?>" id="selectNotes_<?php echo $getSimpleNote->id; ?>" value="<?php echo $getSimpleNote->id; ?>" <?php echo $checked; ?> />
						<?php }else{ ?>
							<input type="checkbox" name="simple_notes[]" class="custom-control-input" id="selectNotes_<?php echo $getSimpleNote->id; ?>" value="<?php echo $getSimpleNote->id; ?>" <?php echo $checked; ?> <?php echo $disabled; ?> />
						<?php } ?>
						<label class="custom-control-label pt-1" for="selectNotes_<?php echo $getSimpleNote->id; ?>"><?php echo $getSimpleNote->notes; ?></label>
					</div>
					<?php
					}
				?>
					</div>
				<?php } ?>
			</div>
			<div class="notesElement notesElement_pb_space " style="display: none;">
				<?php
				$finalNotesElementCountArr = array_count_values( $elementNotesArray );
				if( !empty( $finalNotesElementCountArr ) ){
					$elementNoteLoop = 1;
					foreach( $finalNotesElementCountArr as $noteValue => $noteCount ){
						$checked = "";
						$disabled = "";
						if( $noteCount == $total_items ){
							$checked = "checked";
						}else if( $noteCount != $total_items ){
							$disabled = "disabled";
							$checked = "checked";
						}
						?>
						<div class="btn_list mb-1 element_note_section_loop_<?php echo $elementNoteLoop; ?>" id="element_note_section_loop_<?php echo $elementNoteLoop; ?>">
							<?php /*if( !empty( $checked ) && !empty( $disabled ) ){ ?>
								<input type="checkbox" name="note_element_notes_disabled[]" class="custom-control-input <?php echo $disabled; ?>" id="noteElemSelectNotes_<?php echo sanitize_title( $noteValue ); ?>" value="<?php echo $noteValue; ?>" <?php echo $checked; ?> />
							<?php }else{ ?>
								<input type="checkbox" name="note_element_notes[]" class="custom-control-input" id="noteElemSelectNotes_<?php echo sanitize_title( $noteValue ); ?>" value="<?php echo $noteValue; ?>" <?php echo $checked; ?> <?php echo $disabled; ?> />
							<?php }*/ ?>
							<div class="row">
								<div class="col-md-6 d-flex align-items-center">
									<label class="pt-1" for="noteElemSelectNotes_<?php echo sanitize_title( $noteValue ); ?>"><?php echo $noteValue; ?></label>
								</div>
								<?php if( !empty( $checked ) && !empty( $disabled ) ){
									?>
									<div class="col-md-3">
										<button type="button" style="padding: 6px 15px;" class="w-100 editNoteElementBtn disabled" disabled><?php _e('Edit', CIP_TXTDOMAIN ); ?> <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="<?php _e('Only notes that are comment to every row can be edited. Please update the selection criteria.', CIP_TXTDOMAIN) ?>"></i> </button>
									</div>
									<div class="col-md-3">
										<button type="button" style="padding: 6px 15px;" class="w-100 deleteNoteElementBtn disabled" disabled><?php _e('Delete', CIP_TXTDOMAIN ); ?> <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="<?php _e('Only notes that are comment to every row can be deleted. Please update the selection criteria.', CIP_TXTDOMAIN) ?>"></i> </button>
									</div>
									<?php
								}else if( !empty( $checked ) ){
									?>
									<div class="col-md-3">
										<button type="button" style="padding: 6px 15px;" class="w-100 editNoteElementBtn" data-noteelem="<?php echo $elementNoteLoop ?>"><?php _e('Edit', CIP_TXTDOMAIN ); ?></button>
									</div>
									<div class="col-md-3">
										<button type="button" style="padding: 6px 15px;" class="w-100 deleteNoteElementBtn" data-noteelem="<?php echo $elementNoteLoop ?>"><?php _e('Delete', CIP_TXTDOMAIN ); ?></button>
									</div>
									<input type="hidden" name="noteElemSelectNotes<?php echo $elementNoteLoop ?>" value="<?php echo $noteValue; ?>" />
									<?php
								}
								?>
							</div>
						</div>
						<?php
						$elementNoteLoop++;
					}
				}
				?>
				<?php if( $elementNoteMaxCount ){ ?>
					<button type="button" style="padding: 6px 15px;" class="disabled"><?php _e('Add New', CIP_TXTDOMAIN ); ?> <i class="fa fa-info-circle" data-toggle="tooltip" data-placement="top" title="<?php _e('One or more of the selected rows already contain the maximum number (5) notes.', CIP_TXTDOMAIN) ?>"></i> </button>
				<?php }else{ ?>
					<div class="row border-top addnewelement_row_space">
						<div class="col-md-9 form-group m-0">
							<input type="text" class="form-control" id="addnewNoteElementNotes" name="addnewNoteElementNotes" placeholder="<?php _e('Note *', CIP_TXTDOMAIN); ?>" maxlength="100" />
						</div>
						<div class="col-md-3 form-group m-0">
							<button type="button" style="padding: 6px 15px;" class="w-100 addNewNoteElementBtn"><?php _e('Add New', CIP_TXTDOMAIN ); ?></button>
						</div>
					</div>
				<?php } ?>
			</div>
			<div class="sa_csr_holder_btns">
				<input type="submit" class="btn" name="submit" value="<?php _e('Save', CIP_TXTDOMAIN); ?>" />
				<input type="button" class="btn" name="cancel" data-dismiss="modal" value="<?php _e('Cancel', CIP_TXTDOMAIN); ?>" />
			</div>
		</form>
		<form class="deleteNoteElementNotesFrm" name="deleteNoteElementNotesFrm" id="deleteNoteElementNotesFrm">
			<input type="hidden" name="note_element_delete_notes_hidden" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyDeleteNoteElementNotesyX_'); ?>" />
			<input type="hidden" name="action" value="deletenoteelementnotes_act" />
		</form>
		<?php if( !$elementNoteMaxCount ){ ?>
		<form class="addnewNoteElementNotesFrm" name="addnewNoteElementNotesFrm" id="addnewNoteElementNotesFrm">
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyAddNewNoteElementNotesyX_'); ?>" />
			<input type="hidden" name="action" value="addnewnoteelementnotes_act" />
		</form>
		<?php } ?>
		<?php
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_csrEditNotesAction', 'csrEditNotesAction_callback' );
function csrEditNotesAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCSREditNotesSimpleCSRXy_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}
		$sessionSaCsrSelectionDataEncrypt = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		$sessionSaCsrSelectionData = array();
		if( !empty( $sessionSaCsrSelectionDataEncrypt ) ){
			foreach( $sessionSaCsrSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_SASELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSaCsrSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}
		/* $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('You must enable Google Autheticator 2FA',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		if( true ){
		// if( !empty( $_POST['sasm_ga_otp'] ) ){
			// $google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( true ){
			// if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ga_otp'], 0) ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$filter_qry = "";
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				if( $filterBy != 'none' ){
					$filters['notes_external'] = trim( $filterByValue );
				}
				$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
				$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else if( $filterKey == 'username' ){
							$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
						}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else if( $filterKey == 'notes_external' ){
							if( $filterBy != 'none' ){
								if( $filterBy == 'is_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
								}else if( $filterBy == 'is_not_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
								}else if( $filterBy == 'contains_text' ){
									$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'does_not_contains_text' ){
									$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'starts_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
								}else if( $filterBy == 'ends_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
								}else if( $filterBy == 'is_exactly' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
								}
							}
						}else{
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}

				$tableSimpleNotes = $wpdb->prefix.'simple_notes';
				$getSimpleNotes = $wpdb->get_results("SELECT * FROM $tableSimpleNotes WHERE 1 AND `status`=1");
				$allSimpleNotesArr = array();
				if( !empty( $getSimpleNotes ) ){
					foreach( $getSimpleNotes as $getSimpleNote ){
						$allSimpleNotesArr[$getSimpleNote->id] = $getSimpleNote->notes;
					}
				}
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
				if( $getCurrentMembers ){
					foreach( $getCurrentMembers as $getCurrentMember ){

						$updateNoteArr = array();
						$notesArray = array();
						$rowNotes = explode("|",$getCurrentMember->notes_external);
						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								if( !empty( trim( $rowNote ) ) ){
									$notesArray[] = trim( $rowNote );
									if( isset( $_POST['simple_notes_disabled'] ) && !empty( $_POST['simple_notes_disabled'] ) ){
										foreach( $_POST['simple_notes_disabled'] as $simple_notes_disabled_id ){
											$disabledVal = $allSimpleNotesArr[ $simple_notes_disabled_id ];
											if( $disabledVal == trim( $rowNote ) ){
												$updateNoteArr[] = $disabledVal;
											}
										}
									}
									if( !in_array( trim( $rowNote ), $allSimpleNotesArr ) ){
										$updateNoteArr[] = trim( $rowNote );
									}
								}
							}
						}

						if( isset( $_POST['simple_notes'] ) && !empty( $_POST['simple_notes'] ) ){
							foreach( $_POST['simple_notes'] as $simple_notes_id ){
								$enableVal = $allSimpleNotesArr[ $simple_notes_id ];
								$updateNoteArr[] = $enableVal;
							}
						}
						$notesString = "";
						$updateNoteArr = array_unique($updateNoteArr);
						if( !empty( $updateNoteArr ) ){
							foreach( $updateNoteArr as $updateNoteArrVal ){
								$notesString .= '| '. $updateNoteArrVal .' |';
							}
							$notesString = notes_trim_pipe( $notesString );
						}
						$updateNotes = $wpdb->update( $tableTokenHolder, [ 'notes_external' => $notesString ], [ 'id' => $getCurrentMember->id ] );
					}
					$out = array( "error" => 0,'msg' => __('Notes updated',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_editnoteelementnotes_act', 'editnoteelementnotes_act_callback' );
function editnoteelementnotes_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyEditNoteElementNotesyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}
		$sessionSaCsrSelectionDataEncrypt = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		$sessionSaCsrSelectionData = array();
		if( !empty( $sessionSaCsrSelectionDataEncrypt ) ){
			foreach( $sessionSaCsrSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_SASELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSaCsrSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}
		if( empty( $_POST['note_element_notes'] ) || empty( $_POST['note_element_notes_hidden'] ) ){
			$out = array( "error" => 1,'msg' => __('Please add note',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		/* $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('You must enable Google Autheticator 2FA',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		if( true ){
		// if( !empty( $_POST['sasm_ga_otp'] ) ){
			// $google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( true ){
			// if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ga_otp'], 0) ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$filter_qry = "";
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				if( $filterBy != 'none' ){
					$filters['notes_external'] = trim( $filterByValue );
				}
				$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
				$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else if( $filterKey == 'username' ){
							$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
						}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else if( $filterKey == 'notes_external' ){
							if( $filterBy != 'none' ){
								if( $filterBy == 'is_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
								}else if( $filterBy == 'is_not_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
								}else if( $filterBy == 'contains_text' ){
									$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'does_not_contains_text' ){
									$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'starts_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
								}else if( $filterBy == 'ends_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
								}else if( $filterBy == 'is_exactly' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
								}
							}
						}else{
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
				if( $getCurrentMembers ){

					foreach( $getCurrentMembers as $getCurrentMember ){
						$rowNotes = explode("|",$getCurrentMember->notes_external);
						$elementNotesDupArray = array();
						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								$trimRowNote = trim( $rowNote );
								if( !empty( $trimRowNote ) ){
									$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
									if( $isNoteElement ){
										$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
										$rowNotesElement = explode(" ; ",$notesResult);
										if( !empty( $rowNotesElement ) ){
											foreach( $rowNotesElement as $rowNotesElem ){
												$elementNotesDupArray[] = $rowNotesElem;
											}
										}
									}
								}
							}
						}
						if( in_array( $_POST['note_element_notes'], $elementNotesDupArray ) ){
							$out = array( "error" => 1,'msg' => __('Already have same note',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
					foreach( $getCurrentMembers as $getCurrentMember ){

						$updateNoteArr = array();
						$notesArray = array();
						$rowNotes = explode("|",$getCurrentMember->notes_external);

						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								$elementNotesArray = array();
								$trimRowNote = trim( $rowNote );
								if( !empty( $trimRowNote ) ){
									$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
									if( $isNoteElement ){
										$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
										$rowNotesElement = explode(" ; ",$notesResult);
										if( !empty( $rowNotesElement ) ){
											foreach( $rowNotesElement as $rowNotesElem ){
												if( $rowNotesElem === $_POST['note_element_notes_hidden'] ){
													$elementNotesArray[] = $_POST['note_element_notes'];
												}else{
													$elementNotesArray[] = $rowNotesElem;
												}
											}
											if( !empty( $elementNotesArray ) ){
												$newNote = 'Notes : '. implode(" ; ",$elementNotesArray);
												$updateNoteArr[] = $newNote;
											}
										}
									}else{
										$updateNoteArr[] = $trimRowNote;
									}
								}
							}
						}

						$notesString = "";
						$updateNoteArr = array_unique($updateNoteArr);
						if( !empty( $updateNoteArr ) ){
							foreach( $updateNoteArr as $updateNoteArrVal ){
								$notesString .= '| '. $updateNoteArrVal .' |';
							}
							$notesString = notes_trim_pipe( $notesString );
						}
						$updateNotes = $wpdb->update( $tableTokenHolder, [ 'notes_external' => $notesString ], [ 'id' => $getCurrentMember->id ] );
					}
					$out = array( "error" => 0,'msg' => __('Notes updated',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_deletenoteelementnotes_act', 'deletenoteelementnotes_act_callback' );
function deletenoteelementnotes_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyDeleteNoteElementNotesyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}
		$sessionSaCsrSelectionDataEncrypt = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		$sessionSaCsrSelectionData = array();
		if( !empty( $sessionSaCsrSelectionDataEncrypt ) ){
			foreach( $sessionSaCsrSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_SASELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSaCsrSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}
		if( empty( $_POST['note_element_delete_notes_hidden'] ) ){
			$out = array( "error" => 1,'msg' => __('Undefined note to delete. Please try again',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		/* $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('You must enable Google Autheticator 2FA',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		if( true ){
		// if( !empty( $_POST['sasm_ga_otp'] ) ){
			// $google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( true ){
			// if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ga_otp'], 0) ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$filter_qry = "";
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				if( $filterBy != 'none' ){
					$filters['notes_external'] = trim( $filterByValue );
				}
				$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
				$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else if( $filterKey == 'username' ){
							$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
						}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else if( $filterKey == 'notes_external' ){
							if( $filterBy != 'none' ){
								if( $filterBy == 'is_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
								}else if( $filterBy == 'is_not_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
								}else if( $filterBy == 'contains_text' ){
									$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'does_not_contains_text' ){
									$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'starts_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
								}else if( $filterBy == 'ends_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
								}else if( $filterBy == 'is_exactly' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
								}
							}
						}else{
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
				if( $getCurrentMembers ){
					foreach( $getCurrentMembers as $getCurrentMember ){

						$updateNoteArr = array();
						$notesArray = array();
						$rowNotes = explode("|",$getCurrentMember->notes_external);

						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								$elementNotesArray = array();
								$trimRowNote = trim( $rowNote );
								if( !empty( $trimRowNote ) ){
									$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
									if( $isNoteElement ){
										$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
										$rowNotesElement = explode(" ; ",$notesResult);
										if( !empty( $rowNotesElement ) ){
											foreach( $rowNotesElement as $rowNotesElem ){
												if( $rowNotesElem === $_POST['note_element_delete_notes_hidden'] ){
													//nothing to delete
													//$elementNotesArray[] = $_POST['note_element_notes'];
												}else{
													$elementNotesArray[] = $rowNotesElem;
												}
											}
											if( !empty( $elementNotesArray ) ){
												$newNote = 'Notes : '. implode(" ; ",$elementNotesArray);
												$updateNoteArr[] = $newNote;
											}
										}
									}else{
										$updateNoteArr[] = $trimRowNote;
									}
								}
							}
						}

						$notesString = "";
						$updateNoteArr = array_unique($updateNoteArr);
						if( !empty( $updateNoteArr ) ){
							foreach( $updateNoteArr as $updateNoteArrVal ){
								$notesString .= '| '. $updateNoteArrVal .' |';
							}
							$notesString = notes_trim_pipe( $notesString );
						}
						$updateNotes = $wpdb->update( $tableTokenHolder, [ 'notes_external' => $notesString ], [ 'id' => $getCurrentMember->id ] );
					}
					$out = array( "error" => 0,'msg' => __('Notes updated',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_addnewnoteelementnotes_act', 'addnewnoteelementnotes_act_callback' );
function addnewnoteelementnotes_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyAddNewNoteElementNotesyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$filter_qry = "";
		$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
		$filterBy = "";
		$filterByValue = "";
		if( !empty( $filterByConditions ) ){
			$filterBy = $filterByConditions['filter_condition_type'];
			$filterByValue = $filterByConditions['filter_condition_value'];
		}
		$sessionSaCsrSelectionDataEncrypt = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
		$sessionSaCsrSelectionData = array();
		if( !empty( $sessionSaCsrSelectionDataEncrypt ) ){
			foreach( $sessionSaCsrSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_SASELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSaCsrSelectionData[] = $decryptedUserId;
			}
		}
		$sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSaCsrSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSaCsrSelectionData) .')';
		}
		if( empty( $_POST['addnewNoteElementNotes'] ) ){
			$out = array( "error" => 1,'msg' => __('Please add note.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		/* $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('You must enable Google Autheticator 2FA',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		} */
		if( true ){
		// if( !empty( $_POST['sasm_ga_otp'] ) ){
			// $google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( true ){
			// if( $google2fa->verifyKey($google_auth_key, $_POST['sasm_ga_otp'], 0) ){
				global $wpdb;
				$tableTokenHolder = $wpdb->prefix.'token_holder';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$filter_qry = "";
				$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
				if( $filterBy != 'none' ){
					$filters['notes_external'] = trim( $filterByValue );
				}
				$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
				$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date');
				if( !empty( $filters ) ){
					foreach( $filters as $filterKey => $filterData ){
						if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
							$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						}else if( $filterKey == 'username' ){
							$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
						}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
							if( str_contains($filterData, '-') ){ //between
								$filterDataMinMax = explode('-', $filterData);
								$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
							}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
								$filter_qry .= " AND `$filterKey` $filterData";
							}else{
								$filter_qry .= " AND `$filterKey` = " . $filterData . "";
							}
						}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
							if( str_contains($filterData, ' - ') ){
								$filterDataMinMax = explode(' - ', $filterData);
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
							}else{
								$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
							}
						}else if( $filterKey == 'notes_external' ){
							if( $filterBy != 'none' ){
								if( $filterBy == 'is_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
								}else if( $filterBy == 'is_not_empty' ){
									$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
								}else if( $filterBy == 'contains_text' ){
									$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'does_not_contains_text' ){
									$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
								}else if( $filterBy == 'starts_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
								}else if( $filterBy == 'ends_with' ){
									$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
								}else if( $filterBy == 'is_exactly' ){
									$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
								}
							}
						}else{
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}
				$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $filter_qry $sessionDataQry");
				if( $getCurrentMembers ){
					foreach( $getCurrentMembers as $getCurrentMember ){
						$rowNotes = explode("|",$getCurrentMember->notes_external);
						$elementNotesDupArray = array();
						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								$trimRowNote = trim( $rowNote );
								if( !empty( $trimRowNote ) ){
									$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
									if( $isNoteElement ){
										$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
										$rowNotesElement = explode(" ; ",$notesResult);
										if( !empty( $rowNotesElement ) ){
											foreach( $rowNotesElement as $rowNotesElem ){
												$elementNotesDupArray[] = $rowNotesElem;
											}
										}
									}
								}
							}
						}
						if( in_array( $_POST['addnewNoteElementNotes'], $elementNotesDupArray ) ){
							$out = array( "error" => 1,'msg' => __('Already have same note',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}
					foreach( $getCurrentMembers as $getCurrentMember ){

						$updateNoteArr = array();
						$notesArray = array();
						$rowNotes = array_filter( explode("|",$getCurrentMember->notes_external) );

						$isFoundNoteElement = false;
						if( !empty( $rowNotes ) ){
							foreach( $rowNotes as $rowNote){
								$elementNotesArray = array();
								$trimRowNote = trim( $rowNote );
								if( !empty( $trimRowNote ) ){
									$isNoteElement = substr( $trimRowNote, 0, 7 ) === "Notes :";
									if( $isNoteElement ){
										$isFoundNoteElement = true;
										$notesResult = trim(preg_replace("/^Notes :/", "", $trimRowNote));
										$rowNotesElement = explode(" ; ",$notesResult);
										if( !empty( $rowNotesElement ) ){
											foreach( $rowNotesElement as $rowNotesElem ){
												if( !empty( $rowNotesElem ) ){
													$elementNotesArray[] = $rowNotesElem;
												}
											}
											if( !empty( $_POST['addnewNoteElementNotes'] ) ){
												$elementNotesArray[] = $_POST['addnewNoteElementNotes'];
											}
											if( !empty( $elementNotesArray ) ){
												$newNote = 'Notes : '. implode(" ; ",$elementNotesArray);
												$updateNoteArr[] = $newNote;
											}
										}
									}else{
										$updateNoteArr[] = $trimRowNote;
									}
								}
							}
							if( !$isFoundNoteElement ){
								$elementNotesArray = array();
								if( !empty( $_POST['addnewNoteElementNotes'] ) ){
									$elementNotesArray[] = $_POST['addnewNoteElementNotes'];
								}
								if( !empty( $elementNotesArray ) ){
									$newNote = 'Notes : '. implode(" ; ",$elementNotesArray);
									$updateNoteArr[] = $newNote;
								}
							}
						}else{
							$elementNotesArray = array();
							if( !empty( $_POST['addnewNoteElementNotes'] ) ){
								$elementNotesArray[] = $_POST['addnewNoteElementNotes'];
							}
							if( !empty( $elementNotesArray ) ){
								$newNote = 'Notes : '. implode(" ; ",$elementNotesArray);
								$updateNoteArr[] = $newNote;
							}
						}

						$notesString = "";
						$updateNoteArr = array_unique($updateNoteArr);
						if( !empty( $updateNoteArr ) ){
							foreach( $updateNoteArr as $updateNoteArrVal ){
								$notesString .= '| '. $updateNoteArrVal .' |';
							}
							$notesString = notes_trim_pipe( $notesString );
						}
						$updateNotes = $wpdb->update( $tableTokenHolder, [ 'notes_external' => $notesString ], [ 'id' => $getCurrentMember->id ] );
					}
					$out = array( "error" => 0,'msg' => __('Notes updated',CIP_TXTDOMAIN) );
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_create_simple_note_act', 'create_simple_note_act_callback');
function create_simple_note_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPcreateSimpleNoteCIPY_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableSimpleNotes = $wpdb->prefix.'simple_notes';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$getAlreadyHaveNote = $wpdb->get_row("SELECT * FROM $tableSimpleNotes WHERE `notes` = '".$_POST['simple_notes']."'");
		if( $getAlreadyHaveNote ){
			$out = array( "error" => 1,'msg' => __('Failed to add note, due to already have.',CIP_TXTDOMAIN) );
		}else{
			$insert = $wpdb->insert( $tableSimpleNotes, ['notes' => $_POST['simple_notes'], 'status' => 1, '_date' => date_i18n('Y-m-d H:i:s')] );
			if( $insert ){
				$out = array( "error" => 0,'msg' => __('Note added',CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_get_simplenotes_action', 'cip_get_simplenotes_action_callback' );
function cip_get_simplenotes_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableSimpleNotes = $wpdb->prefix.'simple_notes';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$note_id = preg_replace(sprintf('/%s/', md5('CIP_SimpleNotes_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $note_id . md5('CIP_SimpleNotes_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableSimpleNotes WHERE 1 AND id = ".$note_id."");
			if( $getData ){
				$getAlreadyHaveNote = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE `notes_external` LIKE '%" . $getData->notes . "%'");
				if( $getAlreadyHaveNote ){
					$out = array( "error" => 1,'msg' => __('Failed to update note, due to already assign to member notes.',CIP_TXTDOMAIN));
					echo wp_json_encode( $out );
					exit;
				}
				ob_start();
				?>
				<form class="edit_simple_notes_frm" id="edit_simple_notes_frm" name="edit_simple_notes_frm">
					<div class="form-group">
						<h5><?php _e('Edit Notes', CIP_TXTDOMAIN); ?></h5>
					</div>
					<div class="form-group">
						<input type="text" class="form-control" id="simple_notes" name="simple_notes" placeholder="<?php _e('Note *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->notes; ?>" />
					</div>
					<button type="submit" class="btn btn-secondary"><?php _e('Update', CIP_TXTDOMAIN); ?></button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
					<input type="hidden" name="action" value="update_simple_note_act" />
					<input type="hidden" name="note_id" value="<?php echo $_POST['thisId']; ?>" />
					<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
				</form>
				<?php
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_update_simple_note_act', 'cip_update_simple_note_act_callback' );
function cip_update_simple_note_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableSimpleNotes = $wpdb->prefix.'simple_notes';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$decryptedId_raw = base64_decode( $_POST['note_id'] );
		$note_id = preg_replace(sprintf('/%s/', md5('CIP_SimpleNotes_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $note_id . md5('CIP_SimpleNotes_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableSimpleNotes WHERE 1 AND id = ".$note_id."");
			if( $getData && !empty( $_POST['simple_notes'] ) ){
				$getAlreadyHaveNote = $wpdb->get_row("SELECT * FROM $tableSimpleNotes WHERE `notes` = '".$_POST['simple_notes']."'");
				if( $getAlreadyHaveNote ){
					$out = array( "error" => 1,'msg' => __('Failed to update note, due to already have.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$getAlreadyHaveNote = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE `notes_external` LIKE '%" . $getData->notes . "%'");
				if( $getAlreadyHaveNote ){
					$out = array( "error" => 1,'msg' => __('Failed to update note, due to already assign to member notes.',CIP_TXTDOMAIN));
				}else{
					$update = $wpdb->update( $tableSimpleNotes, [ 'notes' => $_POST['simple_notes'], '_date' => date_i18n('Y-m-d H:i:s') ], [ 'id' => $note_id ] );
					if( $update ){
						$out = array( "error" => 0,'msg' => __('Note updated',CIP_TXTDOMAIN) );
					}else{
						$out = array( "error" => 1,'msg' => __('Update failed',CIP_TXTDOMAIN) );
					}
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_delete_simplenotes_action', 'cip_delete_simplenotes_action_callback' );
function cip_delete_simplenotes_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableSimpleNotes = $wpdb->prefix.'simple_notes';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$note_id = preg_replace(sprintf('/%s/', md5('CIP_SimpleNotes_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $note_id . md5('CIP_SimpleNotes_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableSimpleNotes WHERE 1 AND id = ".$note_id."");
			if( $getData ){
				$getAlreadyHaveNote = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE `notes_external` LIKE '%" . $getData->notes . "%'");
				if( $getAlreadyHaveNote ){
					$out = array( "error" => 1,'msg' => __('Failed to delete note, due to already assign to member notes.',CIP_TXTDOMAIN));
				}else{
					$deleting = $wpdb->delete( $tableSimpleNotes, ['id' => $note_id] );
					if( $deleting ){
						$out = array( "error" => 0,'msg' => __('Note deleted',CIP_TXTDOMAIN));
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to delete note',CIP_TXTDOMAIN));
					}
				}

			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_partialDeliverNowAct', 'cip_partialDeliverNowAct_callback' );
function cip_partialDeliverNowAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'], '_CIPXyZ_PartialDeliverNow_ZyXCIP_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$partialDeliverData = $_POST['delivery_amount'];
		if( !empty( $partialDeliverData ) ){
			foreach( $partialDeliverData as $partialData ){
				if( is_array( $partialData ) ){
					$decryptedIdRaw = base64_decode( $partialData['id'] );
					$decryptedTokenId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
					$partialDeliveryFinalIds[] = $decryptedTokenId;
				}
			}
		}
		$csrPartialResults = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 AND `id` IN (". implode(',', $partialDeliveryFinalIds) .") ORDER BY `id` DESC");

		$tokenTypeArray = array();
		$tokenTypeText = "";
		if( $csrPartialResults ){
			foreach( $csrPartialResults as $csrPartialResult ){
				$tokenTypeArray[ strtoupper( $csrPartialResult->token ) ] = strtoupper( $csrPartialResult->token );
				$tokenTypeText = strtoupper( $csrPartialResult->token );
			}
		}

		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$delivered = false;
		if( !empty( $_POST['partial_deliver_ga_otp'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['partial_deliver_ga_otp'], 0) ){
				// $tempData = array();
				$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 = __('Deposit', CIP_TXTDOMAIN);
				$deliveryBatchId = get_option('delivery_batch_id');
				if( !empty( $deliveryBatchId ) ){
					$deliveryBatchId = $deliveryBatchId + 1;
				}else{
					$deliveryBatchId = 1;
				}
				$withdrawBatchUpdate = false;
				$partialDeliverData = $_POST['delivery_amount'];
				if( !empty( $partialDeliverData ) ){
					foreach( $partialDeliverData as $partialData ){
						if( is_array( $partialData ) ){
							$decryptedIdRaw = base64_decode( $partialData['id'] );
							$decryptedTokenId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
							if( !empty( $decryptedTokenId ) ){
								$getData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE `id`=". $decryptedTokenId ."");

								// $tempData[] = $getData;
								if( $getData && !empty( $partialData['amount'] ) ){

									$amount_due = ( $getData->amount_due - $partialData['amount'] );
									$csr_amount_issued = ( $getData->csr_amount_issued + $partialData['amount'] );
									if( $amount_due >= 0 ){

										$corp_approved = 'Partially Delivered';
										if( $amount_due == 0 ){
											$corp_approved = 'Delivered';
										}
										$data = array(
											'amount_due' 		=> $amount_due,
										//	'csr_amount_issued' => $csr_amount_issued,
											'date_1' 			=> date_i18n('d/m/Y'),
											'corp_approved' 	=> $corp_approved,
										);
										if( $getData->pool_ref == 'SPC-CRSM' ){
											$data = wp_parse_args( ['text_9' => 'management'], $data );
										}
										$where = array( 'id' => $getData->id );
										$update = $wpdb->update( $tableTokenHolder, $data, $where );
										if( $update ){
											$delivered = true;
											$logs = sprintf( __('Partial '. $tokenTypeText .' Delivered by %s at %s. email: %s, username: %s, reference: %s, delivered amount: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $getData->email, $getData->username, $getData->reference, $partialData['amount'] );
											create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
											$deliveryBatchIdPrefix = sprintf('%03d', $deliveryBatchId);
											$referenceNew = $getData->reference . '-' . $deliveryBatchIdPrefix;
											$userData = get_user_by('email', $getData->email);
											$user_id = 0;
											if( $userData ){
												$user_id = $userData->ID;
											}

											//short description
											$updateNoteArr = array();
											$rowNotes = explode("|", $getData->notes_external);
											if( !empty( $rowNotes ) ){
												foreach( $rowNotes as $rowNote){
													$rowNote = trim( $rowNote );
													if( !empty( $rowNote ) ){
														$updateNoteArr[] = $rowNote;
													}
												}
											}
											$poolPatternMpp  = "/^MPP-(.*?)/i";
											$awardDeliveryPool = array( 'C', 'F', 'J', 'H' );
											$csrRedemptionDelivery = array( 'A', 'B', 'D', 'E' );

											$csrDelivery = array( 'G','K', 'DI', 'BNS' );
											$csrDeliveryWeekPattern = "/^Week-(.*?)/i";
											$csrDeliveryMonthYear = array(
												"/^January_[0-9]{4}/i",
												"/^February_[0-9]{4}/i",
												"/^March_[0-9]{4}/i",
												"/^April_[0-9]{4}/i",
												"/^May_[0-9]{4}/i",
												"/^June_[0-9]{4}/i",
												"/^July_[0-9]{4}/i",
												"/^August_[0-9]{4}/i",
												"/^September_[0-9]{4}/i",
												"/^October_[0-9]{4}/i",
												"/^November_[0-9]{4}/i",
												"/^December_[0-9]{4}/i",
											);

											$csrSpecialPoolsPattern  = "/^SPC-(.*?)/i";

											if( preg_match($poolPatternMpp, $getData->pool_ref ) ){
												$short_description = __( 'Bonus Purchase Pool delivery', CIP_TXTDOMAIN );
											}else if( in_array( $getData->pool_ref, $awardDeliveryPool ) ){
												$short_description = __( 'Discretionary award delivery', CIP_TXTDOMAIN );
											}else if( in_array( $getData->pool_ref, $csrRedemptionDelivery ) ){
												$short_description = __( $tokenTypeText . ' redemption delivery', CIP_TXTDOMAIN );
											}else if(
												in_array( $getData->pool_ref, $csrDelivery ) ||
												preg_match($csrDeliveryWeekPattern, $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[0], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[1], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[2], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[3], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[4], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[5], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[6], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[7], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[8], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[9], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[10], $getData->pool_ref ) ||
												preg_match($csrDeliveryMonthYear[11], $getData->pool_ref )
											){
												$short_description = __( $tokenTypeText . ' delivery', CIP_TXTDOMAIN );
											}else if( $getData->pool_ref == 'SPC-CRSM' ){
												$short_description = __( 'Partial delivery', CIP_TXTDOMAIN );
											}else if( preg_match( $csrSpecialPoolsPattern, $getData->pool_ref ) && $getData->pool_ref != 'SPC-CRSM' ){
												$short_description = __( $tokenTypeText . ' redemption delivery', CIP_TXTDOMAIN );
											}else if( in_array( 'Pending 10% distribution.', $updateNoteArr ) || in_array( 'Pending 10% distribution', $updateNoteArr ) ){
												$short_description = __( 'PNP delivery', CIP_TXTDOMAIN );
											}else{
												$short_description = __( 'Partial delivery', CIP_TXTDOMAIN );
											}

											$transactionData = array(
												'user_id'			=>	$user_id,
												'txn_id'			=>	$referenceNew,
												'email'				=>	$getData->email,
												'username'			=>	$getData->username,
												'withdrawal_amount'	=>	0,
												'received_amount'	=>	$partialData['amount'],
												'withdrawal_fee'	=>	0,
												'type'				=>	'deposit',
												'description'		=>	$logs,
												'short_description'	=>	$short_description,
												'_date'				=>	date_i18n('Y-m-d H:i:s'),
												'status'			=>	0,
												'token'				=>	$getData->token,
											);
											$transInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );
											//partially insert new record

											$dataPartially = array(
												'reference'			=>	$referenceNew,
												'eth_address'		=>	$getData->eth_address,
												'csr_amount_issued'	=>	$partialData['amount'],
												'amount_due'		=>	0,
												'username'			=>	$getData->username,
												'first_name'		=>	$getData->first_name,
												'last_name'			=>	$getData->last_name,
												'email'				=>	$getData->email,
												'_user_status'		=>	$getData->_user_status,
												'pool_ref'			=>	$getData->pool_ref,
												'corp_approved'		=>	'Delivered',
												'notes_external'	=>	$getData->notes_external,
												'text_1'			=>	$getData->text_1,
												'text_9'			=>	'management',
												'note_8'			=>	$deliveryBatchId,
												'date_1'			=>	date_i18n('d/m/Y'),
												'last_update'		=>	date_i18n('Y-m-d H:i:s'),
												'token'				=>	$getData->token,
											);
											$insertPartially = $wpdb->insert( $tableTokenHolder, $dataPartially );
											if( $insertPartially ){
												$withdrawBatchUpdate = true;
											}
											//notice of withdrawal request
											$tableCipNotice = $wpdb->prefix.'cip_notice';
											$notificationMessageText = sprintf( __('%s '. $tokenTypeText .' successfully deposited to your '. $tokenTypeText .' wallet.', CIP_TXTDOMAIN), number_format( $partialData['amount'], 2 ) );
											$noticeData = array(
												"email"		=>	$getData->email,
												"username"	=>	'',
												"notice"	=>	$notificationMessageText,
												"status"	=>	1,
												"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
											);
											$wpdb->insert( $tableCipNotice, $noticeData );
											$messageText = sprintf( __('<p class="text-left text-size-18">Your '. $tokenTypeText .' wallet has received a %s '. $tokenTypeText .' deposit.</p><p class="text-left text-size-18"><b>Transaction Reference: %s</b></p>', CIP_TXTDOMAIN), number_format( $partialData['amount'], 2), $getData->reference );
											$message = sprintf( __('<h2>Dear Member,</h2><h3>%s', CIP_TXTDOMAIN), $messageText );
											$htmlContent = mailTemplateHtmlRender( $message );
											if( get_email_send_toggle('deposit') == 1 ){
												wp_mail( $getData->email, $subject, $htmlContent );
											}
										}
									}
								}
							}
						}
					}
					if( $withdrawBatchUpdate ){
						update_option( 'delivery_batch_id', $deliveryBatchId );
					}
					if( $delivered ){
						$out = array( "error" => 0,'msg' => __('Partially delivered',CIP_TXTDOMAIN) );
					}
					// $out['tempData'] = $tempData;
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_clearAllNotificationAct', 'clearAllNotificationAct_callback');
function clearAllNotificationAct_callback(){
	global $wpdb;
	$tableCipNotice = $wpdb->prefix.'cip_notice';
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'], '_XyClearAllNoticationNonceyX_' ) && ( current_user_can( 'member' ) ) ){
		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
		$delete = $wpdb->delete( $tableCipNotice, ['email' => $refAccount] );
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('Notification Cleared.',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_create_sms_alert_act', 'create_sms_alert_act_callback');
function create_sms_alert_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPCreateSmsAlertCIPY_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableSmsAlert = $wpdb->prefix.'sms_alert';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( !empty( $_POST['user_ga_otp'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
				$getAlreadyHaveNumber = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE `number` = '".$_POST['sms_alert']."'");
				if( $getAlreadyHaveNumber ){
					$out = array( "error" => 1,'msg' => __('Failed to add number, due to already have.',CIP_TXTDOMAIN) );
				}else{
					$insert = $wpdb->insert( $tableSmsAlert, ['number' => $_POST['sms_alert'], 'status' => 1, '_date' => date_i18n('Y-m-d H:i:s')] );
					if( $insert ){
						$logs = sprintf( __('SMS Alert number added by %s at %s. number: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $_POST['sms_alert'] );
						create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
						$out = array( "error" => 0,'msg' => __('Number added',CIP_TXTDOMAIN) );
					}
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_delete_sms_alert_act', 'cip_delete_sms_alert_act_callback' );
function cip_delete_sms_alert_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableSmsAlert = $wpdb->prefix.'sms_alert';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( !empty( $_POST['user_ga_otp'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
				$decryptedId_raw = base64_decode( $_POST['_microid'] );
				$numberId = preg_replace(sprintf('/%s/', md5('CIP_SmsAlert_CIP') ), '', $decryptedId_raw);
				if( wp_verify_nonce( $_POST['_micro'], '_YCIPDeleteSmsAlertCIPY_' ) ){
					$getData = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE 1 AND id = ".$numberId."");
					if( $getData ){
						$deleting = $wpdb->delete( $tableSmsAlert, ['id' => $numberId] );
						if( $deleting ){
							$logs = sprintf( __('SMS Alert number deleted by %s at %s. number: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $getData->number );
							create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
							$out = array( "error" => 0,'msg' => __('Number deleted',CIP_TXTDOMAIN));
						}else{
							$out = array( "error" => 1,'msg' => __('Failed to delete number',CIP_TXTDOMAIN));
						}
					}
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_getRetirementBanner', 'cip_getRetirementBanner_callback' );
add_action( 'wp_ajax_nopriv_getRetirementBanner', 'cip_getRetirementBanner_callback' );
function cip_getRetirementBanner_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	global $wpdb;
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';

	$visibility_qry = 'retire_visibility = 3';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	if( is_user_logged_in() ){
		$visibility_qry = '((retire_visibility = 3 OR retire_visibility = 2) OR (email = "'.$refAccount.'" AND retire_visibility = 1))';
	}
	$html = "";
	$getRetirements = $wpdb->get_row("SELECT * FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry ORDER BY RAND()");
	if( $getRetirements ){

		$hiLine = $getRetirements->first_name.' '.$getRetirements->last_name;

		$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$getRetirements->email."' ORDER BY `id` DESC");
		if( $getTokenData ){
			if( !empty( $getTokenData->first_name ) || !empty( $getTokenData->last_name ) ){
				$hiLine = $getTokenData->first_name . ' ' . $getTokenData->last_name;
			}
		}

		$getRetirementSetting = $wpdb->get_row("SELECT * FROM $tableRetirementSetting WHERE email = '".$getRetirements->email."' ");
		if( $getRetirementSetting ){
			if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
				$hiLine = $getRetirementSetting->company_name;
			}
		}

		$retire_amount_val = "";
		$retire_amount = floatval( bcadd( $getRetirements->retire_amount, 0, 2) );
		if (fmod($retire_amount, 1) !== 0.0) {
			$retire_amount_val = number_format( $retire_amount, 2 );
		}else{
			$retire_amount_val = number_format( $retire_amount );
		}
		ob_start();
		?>
		<div id="info_br_popup" class="bottom_right_popup">
			<p><?php echo sprintf( __('%s retired %s CSR representing %s KGs removed from the environment.', CIP_TXTDOMAIN), trim( $hiLine ), $retire_amount_val, number_format( ( $getRetirements->retire_amount / 10 ) ) ); ?></p>
		</div>
		<?php
	}
	$html .= ob_get_clean();
	$out = array( "error" => 0,'html' => $html );
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sm_email_sending_switch_settings_act','cip_sm_email_sending_switch_settings_act_cb');
function cip_sm_email_sending_switch_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_csr_email_sending_switch_settingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){

		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();

		$email_notification_toggle_login = ( get_option('email_notification_toggle_login') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_deposit = ( get_option('email_notification_toggle_deposit') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_withdrawal_request = ( get_option('email_notification_toggle_withdrawal_request') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_withdrawal_complete = ( get_option('email_notification_toggle_withdrawal_complete') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_kyc_status_change = ( get_option('email_notification_toggle_kyc_status_change') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_2fa_enabled_disabled = ( get_option('email_notification_toggle_2fa_enabled_disabled') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_otp_enabled_disabled = ( get_option('email_notification_toggle_otp_enabled_disabled') == 1 ) ? 'Enable' : 'Disable' ;
		$email_notification_toggle_complete_your_kyc = ( get_option('email_notification_toggle_complete_your_kyc') == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_login = ( $_POST['email_notification_switch_toggle_login'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_deposit = ( $_POST['email_notification_switch_toggle_deposit'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_withdrawal_request = ( $_POST['email_notification_switch_toggle_withdrawal_request'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_withdrawal_complete = ( $_POST['email_notification_switch_toggle_withdrawal_complete'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_kyc_status_change = ( $_POST['email_notification_switch_toggle_kyc_status_change'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_2fa_enabled_disabled = ( $_POST['email_notification_switch_toggle_2fa_enabled_disabled'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_otp_enabled_disabled = ( $_POST['email_notification_switch_toggle_otp_enabled_disabled'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_email_notification_toggle_complete_your_kyc = ( $_POST['email_notification_switch_toggle_complete_your_kyc'] == 1 ) ? 'Enable' : 'Disable' ;
		if( isset( $_POST['email_notification_switch_toggle_login'] ) && $_POST['email_notification_switch_toggle_login'] == 1 ){
			update_option( 'email_notification_toggle_login', 1 );
		}else{
			update_option( 'email_notification_toggle_login', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_deposit'] ) && $_POST['email_notification_switch_toggle_deposit'] == 1 ){
			update_option( 'email_notification_toggle_deposit', 1 );
		}else{
			update_option( 'email_notification_toggle_deposit', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_withdrawal_request'] ) && $_POST['email_notification_switch_toggle_withdrawal_request'] == 1 ){
			update_option( 'email_notification_toggle_withdrawal_request', 1 );
		}else{
			update_option( 'email_notification_toggle_withdrawal_request', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_withdrawal_complete'] ) && $_POST['email_notification_switch_toggle_withdrawal_complete'] == 1 ){
			update_option( 'email_notification_toggle_withdrawal_complete', 1 );
		}else{
			update_option( 'email_notification_toggle_withdrawal_complete', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_kyc_status_change'] ) && $_POST['email_notification_switch_toggle_kyc_status_change'] == 1 ){
			update_option( 'email_notification_toggle_kyc_status_change', 1 );
		}else{
			update_option( 'email_notification_toggle_kyc_status_change', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_2fa_enabled_disabled'] ) && $_POST['email_notification_switch_toggle_2fa_enabled_disabled'] == 1 ){
			update_option( 'email_notification_toggle_2fa_enabled_disabled', 1 );
		}else{
			update_option( 'email_notification_toggle_2fa_enabled_disabled', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_otp_enabled_disabled'] ) && $_POST['email_notification_switch_toggle_otp_enabled_disabled'] == 1 ){
			update_option( 'email_notification_toggle_otp_enabled_disabled', 1 );
		}else{
			update_option( 'email_notification_toggle_otp_enabled_disabled', 0 );
		}
		if( isset( $_POST['email_notification_switch_toggle_complete_your_kyc'] ) && $_POST['email_notification_switch_toggle_complete_your_kyc'] == 1 ){
			update_option( 'email_notification_toggle_complete_your_kyc', 1 );
		}else{
			update_option( 'email_notification_toggle_complete_your_kyc', 0 );
		}

		$valueData[] = sprintf( __('Email send switch update by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );

		$valueData[] = sprintf( __('Login : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_login, $new_email_notification_toggle_login );
		$valueData[] = sprintf( __('Deposit : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_deposit, $new_email_notification_toggle_deposit );
		$valueData[] = sprintf( __('Withdrawal request : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_withdrawal_request, $new_email_notification_toggle_withdrawal_request );
		$valueData[] = sprintf( __('Withdrawal complete : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_withdrawal_complete, $new_email_notification_toggle_withdrawal_complete );
		$valueData[] = sprintf( __('KYC status change : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_kyc_status_change, $new_email_notification_toggle_kyc_status_change );
		$valueData[] = sprintf( __('2FA enabled / disabled : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_2fa_enabled_disabled, $new_email_notification_toggle_2fa_enabled_disabled );
		$valueData[] = sprintf( __('OTP enabled / disabled : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_otp_enabled_disabled, $new_email_notification_toggle_otp_enabled_disabled );
		$valueData[] = sprintf( __('Complete your KYC : %s to %s', CIP_TXTDOMAIN), $email_notification_toggle_complete_your_kyc, $new_email_notification_toggle_complete_your_kyc );

		$message = implode( PHP_EOL, $valueData);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );

		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sm_sms_sending_switch_settings_act','cip_sm_sms_sending_switch_settings_act_cb');
function cip_sm_sms_sending_switch_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxsm_csr_sms_sending_switch_settingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){

		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();

		$sms_notification_toggle_admin_login = ( get_option('sms_notification_toggle_admin_login') == 1 ) ? 'Enable' : 'Disable' ;
		$sms_notification_toggle_batch_delivery = ( get_option('sms_notification_toggle_batch_delivery') == 1 ) ? 'Enable' : 'Disable' ;
		$sms_notification_toggle_batch_distribution = ( get_option('sms_notification_toggle_batch_distribution') == 1 ) ? 'Enable' : 'Disable' ;
		$sms_notification_toggle_csr_holder_update = ( get_option('sms_notification_toggle_csr_holder_update') == 1 ) ? 'Enable' : 'Disable' ;
		$sms_notification_toggle_alert_disabled = ( get_option('sms_notification_toggle_alert_disabled') == 1 ) ? 'Enable' : 'Disable' ;
		$sms_notification_toggle_sms_balance_below = ( get_option('sms_notification_toggle_sms_balance_below') == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_admin_login = ( $_POST['sms_notification_switch_toggle_admin_login'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_batch_delivery = ( $_POST['sms_notification_switch_toggle_batch_delivery'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_batch_distribution = ( $_POST['sms_notification_switch_toggle_batch_distribution'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_csr_holder_update = ( $_POST['sms_notification_switch_toggle_csr_holder_update'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_alert_disabled = ( $_POST['sms_notification_switch_toggle_alert_disabled'] == 1 ) ? 'Enable' : 'Disable' ;
		$new_sms_notification_toggle_sms_balance_below = ( $_POST['sms_notification_switch_toggle_sms_balance_below'] == 1 ) ? 'Enable' : 'Disable' ;
		if( get_sms_send_toggle('alert_disabled') == 1 ){

			$content = "";
			if( $sms_notification_toggle_admin_login == 'Enable' && $new_sms_notification_toggle_admin_login == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('Admin Login', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( $sms_notification_toggle_batch_delivery == 'Enable' && $new_sms_notification_toggle_batch_delivery == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('Batch delivery', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( $sms_notification_toggle_batch_distribution == 'Enable' && $new_sms_notification_toggle_batch_distribution == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('Batch distribution', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( $sms_notification_toggle_csr_holder_update == 'Enable' && $new_sms_notification_toggle_csr_holder_update == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('CSR holder update', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( $sms_notification_toggle_alert_disabled == 'Enable' && $new_sms_notification_toggle_alert_disabled == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('Alert disabled', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( $sms_notification_toggle_sms_balance_below == 'Enable' && $new_sms_notification_toggle_sms_balance_below == 'Disable' ){
				$content .= sprintf(__('Alert %s disabled by %s. ', CIP_TXTDOMAIN), __('SMS balance below', CIP_TXTDOMAIN), $current_user->user_email );
			}
			if( !empty( $content ) ){
				brevo_sms_alert_send( $content );
			}
		}
		if( isset( $_POST['sms_notification_switch_toggle_admin_login'] ) && $_POST['sms_notification_switch_toggle_admin_login'] == 1 ){
			update_option( 'sms_notification_toggle_admin_login', 1 );
		}else{
			update_option( 'sms_notification_toggle_admin_login', 0 );
		}
		if( isset( $_POST['sms_notification_switch_toggle_batch_delivery'] ) && $_POST['sms_notification_switch_toggle_batch_delivery'] == 1 ){
			update_option( 'sms_notification_toggle_batch_delivery', 1 );
		}else{
			update_option( 'sms_notification_toggle_batch_delivery', 0 );
		}
		if( isset( $_POST['sms_notification_switch_toggle_batch_distribution'] ) && $_POST['sms_notification_switch_toggle_batch_distribution'] == 1 ){
			update_option( 'sms_notification_toggle_batch_distribution', 1 );
		}else{
			update_option( 'sms_notification_toggle_batch_distribution', 0 );
		}
		if( isset( $_POST['sms_notification_switch_toggle_csr_holder_update'] ) && $_POST['sms_notification_switch_toggle_csr_holder_update'] == 1 ){
			update_option( 'sms_notification_toggle_csr_holder_update', 1 );
		}else{
			update_option( 'sms_notification_toggle_csr_holder_update', 0 );
		}
		if( isset( $_POST['sms_notification_switch_toggle_alert_disabled'] ) && $_POST['sms_notification_switch_toggle_alert_disabled'] == 1 ){
			update_option( 'sms_notification_toggle_alert_disabled', 1 );
		}else{
			update_option( 'sms_notification_toggle_alert_disabled', 0 );
		}
		if( isset( $_POST['sms_notification_switch_toggle_sms_balance_below'] ) && $_POST['sms_notification_switch_toggle_sms_balance_below'] == 1 ){
			update_option( 'sms_notification_toggle_sms_balance_below', 1 );
		}else{
			update_option( 'sms_notification_toggle_sms_balance_below', 0 );
		}

		$valueData[] = sprintf( __('SMS send switch update by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );

		$valueData[] = sprintf( __('Admin Login : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_admin_login, $new_sms_notification_toggle_admin_login );
		$valueData[] = sprintf( __('Batch delivery : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_batch_delivery, $new_sms_notification_toggle_batch_delivery );
		$valueData[] = sprintf( __('Batch distribution : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_batch_distribution, $new_sms_notification_toggle_batch_distribution );
		$valueData[] = sprintf( __('CSR holder update : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_csr_holder_update, $new_sms_notification_toggle_csr_holder_update );
		$valueData[] = sprintf( __('Alert disabled : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_alert_disabled, $new_sms_notification_toggle_alert_disabled );
		$valueData[] = sprintf( __('SMS balance below : %s to %s', CIP_TXTDOMAIN), $sms_notification_toggle_sms_balance_below, $new_sms_notification_toggle_sms_balance_below );

		$message = implode( PHP_EOL, $valueData);
		$logs = $message;
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );

		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
function get_email_send_toggle( $option ){
	$status = 0;
	$prefix = 'email_notification_toggle_';
	$optionName = $prefix.$option;
	$optionValue = ( !empty( get_option( $optionName ) ) ) ? get_option( $optionName ) : 0 ;
	if( !empty( $optionValue ) ){
		$status = $optionValue;
	}
	return $status;
}
function get_sms_send_toggle( $option ){
	$status = 0;
	$prefix = 'sms_notification_toggle_';
	$optionName = $prefix.$option;
	$optionValue = ( !empty( get_option( $optionName ) ) ) ? get_option( $optionName ) : 0 ;
	if( !empty( $optionValue ) ){
		$status = $optionValue;
	}
	return $status;
}
function sendSmsAlertOnLoggedIn( $user ){
	if( !empty( $user ) ){
		if( $user->has_cap( 'administrator' ) && get_sms_send_toggle('admin_login') == 1 ){
			$content = sprintf(__('%s (admin) logged into CSRnow from IP: %s at %s.', CIP_TXTDOMAIN), $user->user_email, corsairlogin_client_ip(), date_i18n('d/m/Y H:i:s') );
			brevo_sms_alert_send( $content );
		}
	}
}
function brevo_sms_alert_send( $content = "" ){
	global $wpdb;
	$tableSmsAlert = $wpdb->prefix.'sms_alert';
	$getSmsNumbers = $wpdb->get_results("SELECT * FROM $tableSmsAlert WHERE `status`=1");
	if( $getSmsNumbers ){
		$finalBalanceCredit = 0;
		foreach( $getSmsNumbers as $getSmsNumber ){
			if( !empty( $getSmsNumber ) && !empty( $content ) ){
				$body = array(
					'type' => 'transactional',
					'unicodeEnabled' => false,
					'sender' => 'Corsair',
					'recipient' => $getSmsNumber->number,
					'content'	=>	$content
				);
				$body = wp_json_encode( $body );
				$response = wp_remote_post( 'https://api.brevo.com/v3/transactionalSMS/sms', array(
					'method' 	=> 'POST',
					'headers'	=> array(
						'accept'		=>	'application/json',
						'api-key'		=>	'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',
						'content-type'	=>	'application/json',
					),
					'body' 		=> $body,
				) );

				if ( ! is_wp_error( $response ) ) {
					$bodyResponse = json_decode( wp_remote_retrieve_body( $response ), true );
					if( isset( $bodyResponse['messageId'] ) && !empty( $bodyResponse['messageId'] ) ){
						$logs = sprintf( __('SMS alert sent at %s. to telephone number: %s, message: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $getSmsNumber->number, $content );
						create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
						$finalBalanceCredit = $bodyResponse['remainingCredits'];
					}else{
						$logs = sprintf( __('Error at sending SMS Alert at %s. error: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), json_encode( $bodyResponse) );
						create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
					}
				} else {
					$error_message = $response->get_error_message();
					$logs = sprintf( __('Error at sending SMS Alert at %s. error: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $error_message );
					create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
				}
			}
		}

		if( $finalBalanceCredit > 100 ){
			delete_option( 'below100SmsBalanceFlag' );
			delete_option( 'below75SmsBalanceFlag' );
			delete_option( 'below50SmsBalanceFlag' );
		}
		$below100SmsBalanceFlag = get_option('below100SmsBalanceFlag');
		$below75SmsBalanceFlag = get_option('below75SmsBalanceFlag');
		$below50SmsBalanceFlag = get_option('below50SmsBalanceFlag');
		if( $finalBalanceCredit > 0 && $finalBalanceCredit < 100 && $below100SmsBalanceFlag != 1 ){
			if( get_sms_send_toggle('sms_balance_below') == 1 ){
				update_option( 'below100SmsBalanceFlag', 1 );
				$content = sprintf(__('Brevo SMS balance below 100, current balance %s', CIP_TXTDOMAIN), $finalBalanceCredit );
				brevo_sms_low_balance_alert_send( $content );
			}
		}
		if( $finalBalanceCredit > 0 && $finalBalanceCredit < 75 && $below75SmsBalanceFlag != 1 ){
			if( get_sms_send_toggle('sms_balance_below') == 1 ){
				update_option( 'below75SmsBalanceFlag', 1 );
				$content = sprintf(__('Brevo SMS balance below 75, current balance %s', CIP_TXTDOMAIN), $finalBalanceCredit );
				brevo_sms_low_balance_alert_send( $content );
			}
		}
		if( $finalBalanceCredit > 0 && $finalBalanceCredit < 50 && $below50SmsBalanceFlag != 1 ){
			if( get_sms_send_toggle('sms_balance_below') == 1 ){
				update_option( 'below50SmsBalanceFlag', 1 );
				$content = sprintf(__('Brevo SMS balance below 50, current balance %s', CIP_TXTDOMAIN), $finalBalanceCredit );
				brevo_sms_low_balance_alert_send( $content );
			}
		}
	}
}
function brevo_sms_low_balance_alert_send( $content = "" ){
	global $wpdb;
	$tableSmsAlert = $wpdb->prefix.'sms_alert';
	$getSmsNumbers = $wpdb->get_results("SELECT * FROM $tableSmsAlert WHERE `status`=1");
	if( $getSmsNumbers ){
		foreach( $getSmsNumbers as $getSmsNumber ){
			if( !empty( $getSmsNumber ) && !empty( $content ) ){
				$body = array(
					'type' => 'transactional',
					'unicodeEnabled' => false,
					'sender' => 'Corsair',
					'recipient' => $getSmsNumber->number,
					'content'	=>	$content
				);
				$body = wp_json_encode( $body );
				$response = wp_remote_post( 'https://api.brevo.com/v3/transactionalSMS/sms', array(
					'method' 	=> 'POST',
					'headers'	=> array(
						'accept'		=>	'application/json',
						'api-key'		=>	'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',
						'content-type'	=>	'application/json',
					),
					'body' 		=> $body,
				) );

				if ( ! is_wp_error( $response ) ) {
					$bodyResponse = json_decode( wp_remote_retrieve_body( $response ), true );
					if( isset( $bodyResponse['messageId'] ) && !empty( $bodyResponse['messageId'] ) ){
						$logs = sprintf( __('SMS alert sent at %s. to telephone number: %s, message: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $getSmsNumber->number, $content );
						create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
					}else{
						$logs = sprintf( __('Error at sending SMS Alert at %s. error: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), json_encode( $bodyResponse) );
						create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
					}
				} else {
					$error_message = $response->get_error_message();
					$logs = sprintf( __('Error at sending SMS Alert at %s. error: %s', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $error_message );
					create_cip_logs_entery( 0, 'sm', '','sm', $logs, true );
				}
			}
		}
	}
}
function save_maintenance_mode() {
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxmaintenance_form_settingsxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$live_title = sanitize_text_field($_POST['live_title']);
		$live_message = $_POST['live_message'];
		$whole_title = sanitize_text_field($_POST['whole_title']);
		$whole_message = $_POST['whole_message'];
		$retirement_title = sanitize_text_field($_POST['retirement_title']);
		$retirement_message = $_POST['retirement_message'];
		$maintenance_live_option_array = array(
			"title" => $live_title,
			"message" => $live_message,
		);
		$maintenance_whole_option_array = array(
			"title" => $whole_title,
			"message" => $whole_message,
		);
		$maintenance_retirement_option_array = array(
			"title" => $retirement_title,
			"message" => $retirement_message,
		);
		update_option('maintenance_live_option', $maintenance_live_option_array);
		update_option('maintenance_whole_option', $maintenance_whole_option_array);
		update_option('maintenance_retirement_option', $maintenance_retirement_option_array);
		$current_user = wp_get_current_user();
		$logs = sprintf( __('Routine maintenance title & message changed by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'sm', '','sm', $logs, true );
		$out = array( "error" => 0,'msg' => __('Saved',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_save_maintenance_mode', 'save_maintenance_mode');
add_action('wp_ajax_nopriv_save_maintenance_mode', 'save_maintenance_mode');
function custom_logout() {
    if (isset($_GET['action']) && $_GET['action'] === 'logout') {
		$user = wp_get_current_user();
		$logs = sprintf( __('%s logged-out ( at GET action logout ) %s', 'corsair-login'), $user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $user->ID, 'loggedout', '','member', $logs, true );
        wp_logout();
        wp_safe_redirect(home_url()); // Change the URL to your desired destination
        exit;
    }
}
add_action('init', 'custom_logout');
function notes_trim_pipe( $externalNote = "" ){
	$externalNote = trim(preg_replace('/[|]+/', '|', $externalNote));
	if( $externalNote == "|" ){
		$externalNote = "";
	}
	return $externalNote;
}
function cip_trim_notes( $notes ){
	if( !empty( $notes ) ){
		$notes = trim( trim( $notes, "|" ) );
	}
	return $notes;
}
function cipColumnHeaderTooltip( $toolTip = "" ){
	$html = "";
	if( !empty( $toolTip ) ){
		$html = '<span class="fa fa-info-circle" data-toggle-column="tooltip" data-placement="top" title="'.$toolTip.'"></span>';
	}
	return $html;
}
add_action( 'wp_ajax_checkingCsrWRequestDelivery', 'checkingCsrWRequestDelivery_callback' );
function checkingCsrWRequestDelivery_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRWalletRequestDeliveryyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		/* $sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionWdRequestSelectionData'] ) && !empty( $_SESSION['sessionWdRequestSelectionData'] ) ) ? $_SESSION['sessionWdRequestSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		} */
		$withdrawRequestIdsEncrypt = ( isset( $_POST['withdrawRequestIds'] ) && !empty( $_POST['withdrawRequestIds'] ) ) ? $_POST['withdrawRequestIds'] : array();
		$withdrawRequestIdsData = array();
		if( !empty( $withdrawRequestIdsEncrypt ) ){
			foreach( $withdrawRequestIdsEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
				$withdrawRequestIdsData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		/* $sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		} */
		$sessionDataQry = "";
		$sessionDataQry = ' AND `id` IN ('. implode(',', $withdrawRequestIdsData) .')';
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';

		$filter_qry = " AND ( `withdrawal_process_status` != 'Under review' OR `withdrawal_process_status` IS NULL )";
		$filter_qry_under_review = " AND `withdrawal_process_status` = 'Under review'";

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 AND ( `withdrawal_process_status` != 'Under review' OR `withdrawal_process_status` IS NULL ) $sessionDataQry");
		$isNumericColumn = array('withdraw_amount', 'withdrawal_fee', 'received_amount');
		if( !empty( $filters ) ){

			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == 'withdrawal_id' ){
					$filter_qry .= " AND `withdrawal_id`='".$filterData."'";
					$filter_qry_under_review .= " AND `withdrawal_id`='".$filterData."'";
				}else if( $filterKey == 'requested_date' ){

					$dateObject = explode(" - ",$filterData);
					$fromDate = "";
					$toDate = "";
					if( isset( $dateObject[0] ) && isset( $dateObject[1] ) ){
						$fromDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[0]);
						if( $fromDateObj ){
							$fromDate = $fromDateObj->format('Y-m-d');
						}
						$toDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[1]);
						if( $toDateObj ){
							$toDate = $toDateObj->format('Y-m-d');
						}
						if( $fromDate && $toDate ){
							$filter_qry .= " AND (date(`requested_date`) BETWEEN '$fromDate' AND '$toDate')";
							$filter_qry_under_review .= " AND (date(`requested_date`) BETWEEN '$fromDate' AND '$toDate')";
						}
					}

				}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
						$filter_qry_under_review .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
						$filter_qry_under_review .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
						$filter_qry_under_review .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
							$filter_qry_under_review .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'withdrawal_process_status' ){
					if( $filterData == 'Pending' ){
						$filter_qry .= " AND ( `$filterKey` = '" . $filterData . "' OR `$filterKey` IS NULL )";
						$filter_qry_under_review .= " AND ( `$filterKey` = '" . $filterData . "' OR `$filterKey` IS NULL )";
					}else{
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
						$filter_qry_under_review .= " AND `$filterKey` = '" . $filterData . "'";
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					$filter_qry_under_review .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
					$filter_qry_under_review .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
		}

		$getCurrentMembersUnderReview = $wpdb->get_row("SELECT `id` FROM $tableWithdraw WHERE 1 $filter_qry_under_review $sessionDataQry");
		if( $getCurrentMembersUnderReview ){
			$out = array( "error" => 1,'msg' => __('Under review records not allow to proceess.',CIP_TXTDOMAIN), 'test' => "SELECT `id` FROM $tableWithdraw WHERE 1 $filter_qry_under_review $sessionDataQry" );
			echo wp_json_encode( $out );
			exit;
		}

		$getCurrentMembers = $wpdb->get_results("SELECT `token` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry GROUP BY `token`");
		$tokenTypeArray = array();
		$tokenTypeText = "";
		if( $getCurrentMembers ){
			foreach( $getCurrentMembers as $getCurrentMember ){
				$tokenTypeArray[ strtoupper( $getCurrentMember->token ) ] = strtoupper( $getCurrentMember->token );
				$tokenTypeText = strtoupper( $getCurrentMember->token );
			}
		}

		if( empty( $tokenTypeArray ) || count( $tokenTypeArray ) > 1 || empty( $tokenTypeText ) ){
			$out = array( "error" => 1,'msg' => __('Multiple token not allow to proceess.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT(`eth_address`)) FROM $tableWithdraw WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) $filter_qry $sessionDataQry");
		$totalWithdrawalsAmount = 0;
		$receivedAmountData = $wpdb->get_row("SELECT COALESCE(SUM(`received_amount`),0) as `received_amount` FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
		if( $receivedAmountData ){
			$totalWithdrawalsAmount = $receivedAmountData->received_amount;
		}
		if( $totalWithdrawalsAmount <= 0 ){
			$out = array( "error" => 1,'msg' => __('No CSR available for delivery with current selection.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$html = "";
		ob_start();
		?>
		<!-- process_withdrawal_requests_summary_section -->
		<div class="col-12">
			<h5><?php _e('Check the withdrawal summary and click Next', CIP_TXTDOMAIN); ?></h5>
			<p><?php echo sprintf( __('Total withdrawals : %s', CIP_TXTDOMAIN ), $total_items ); ?></p>
			<p><?php echo sprintf( __('Unique %s addresses : %s', CIP_TXTDOMAIN ), $tokenTypeText, $unique_addresses ); ?></p>
			<p><?php echo sprintf( __('Total %s withdrawal amount : %s %s', CIP_TXTDOMAIN ), $tokenTypeText ,number_format( $totalWithdrawalsAmount, 2 ), $tokenTypeText ); ?></p>
		</div>
		<?php
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancel_withdraw_request_action', 'cip_cancel_withdraw_request_action_callback' );
function cip_cancel_withdraw_request_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;

		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_WithdrawalRequestCancel_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_WithdrawalRequestCancel_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND id = ".$id."");
			if( $getData ){
				$requestedDate = "";
				$requestedDateObj = DateTime::createFromFormat('Y-m-d H:i:s', $getData->requested_date);
				if( $requestedDateObj ){
					$requestedDate = $requestedDateObj->format('d/m/Y H:i');
				}
				$fullname = "";
				if( !empty( $getData->first_name ) || !empty( $getData->last_name ) ){
					$fullname = trim( $getData->first_name . ' ' . $getData->last_name );
					if( !empty( $fullname ) ){
						$fullname = "(".$fullname.")";
					}
				}
				$total_step = 3;
				ob_start();
				?>
				<div class="container-fluid">
					<span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>
					<div class="row justify-content-center">
						<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mt-2 mb-2">
							<div class="card">
								<form name="cancelWithdrawRequestFrm" class="cancelWithdrawRequestFrm" id="msform">
									<!-- progressbar -->
									<ul id="progressbar">
										<li class="active" id="fieldmapping"><strong><?php _e('Cancel Withdrawal',CIP_TXTDOMAIN) ?></strong></li>
										<li id="fieldmapping"><strong><?php _e('Confirmation',CIP_TXTDOMAIN) ?></strong></li>
										<li id="fieldmapping"><strong><?php _e('Canceled',CIP_TXTDOMAIN) ?></strong></li>
									</ul>
									<div class="progress">
										<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
									</div>
									<br> <!-- fieldsets -->
									<fieldset class="step_0">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></p>
												</div>
											</div>

											<div class="row text-center align-items-center pb-0">
											<div class="col-12">
												<p><?php echo sprintf( __('You are canceling a withdrawal requested on %s by %s %s for %s CSR to <span class="eth_address_mono">%s</span> address.', CIP_TXTDOMAIN), $requestedDate, $getData->username, $fullname, number_format( $getData->withdraw_amount, 2, '.', '' ), $getData->eth_address ); ?></p>
												<p><?php _e('You should only cancel a withdrawal request with good reason.', CIP_TXTDOMAIN); ?></p>
											</div>
											<div class="col-3"></div>
											<div class="col-6 form-group">
												<label for="cancel_withdrawal_request_reason"><?php _e('Enter the reason for canceling the withdrawal below.', CIP_TXTDOMAIN); ?></label>
												<textarea class="form-control" id="cancel_withdrawal_request_reason" name="cancel_withdrawal_request_reason"></textarea>
											</div>
											<div class="col-3"></div>
											</div>
										</div>
										<input type="button" name="next" class="next action-button" value="Next" />
									</fieldset>

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

											<div class="row text-center justify-content-center">
												<div class="otp_section pb-3">
													<label for="user_ga_otp_cancel"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
													<input type="text" name="user_ga_otp_cancel" id="user_ga_otp_cancel" class="input mb-1" maxlength="6" pattern="{0-9}+" />
													<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
												</div>
											</div>
										</div>
										<input type="button" name="next" class="next action-button" value="Next" /> <input type="button" name="previous" class="previous action-button-previous" value="Previous" />
									</fieldset>
									<fieldset class="step_2">
										<div class="form-card">
											<div class="row">
												<div class="col-12">
													<p class="steps"><?php echo sprintf('Step %s - %s', 3, $total_step); ?></p>
												</div>
											</div>
											<div class="row align-items-center pb-5 cancel_withdraw_request_respose_section"></div>
										</div>
										<input type="button" name="previous" class="action-button-previous close_cancel_withdraw_request" value="Close" />
									</fieldset>
									<input type="hidden" name="action" value="cancelWithdrawRequestAct" />
									<input type="hidden" name="thisId" value="<?php echo $_POST['thisId'] ?>" />
									<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
								</form>
							</div>
						</div>
					</div>
				</div>
				<?php
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancelWithdrawRequestAct', 'cip_cancelWithdrawRequestAct_callback' );
function cip_cancelWithdrawRequestAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( empty( $_POST['cancel_withdrawal_request_reason'] ) ){
			$out = array( "error" => 1,'msg' => __('Please enter reason for canceling the withdrawal',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( !empty( $_POST['user_ga_otp_cancel'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp_cancel'], 0) ){

				$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$decryptedId_raw = base64_decode( $_POST['thisId'] );
				$id = preg_replace(sprintf('/%s/', md5('CIP_WithdrawalRequestCancel_CIP') ), '', $decryptedId_raw);

				if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_WithdrawalRequestCancel_CIP') ) ){
					$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND id = ".$id."");
					if( $getData ){

						$requestedDate = "";
						$requestedDateObj = DateTime::createFromFormat('Y-m-d H:i:s', $getData->requested_date);
						if( $requestedDateObj ){
							$requestedDate = $requestedDateObj->format('d/m/Y H:i');
						}

						$fullname = "";
						if( !empty( $getData->first_name ) || !empty( $getData->last_name ) ){
							$fullname = trim( $getData->first_name . ' ' . $getData->last_name );
							if( !empty( $fullname ) ){
								$fullname = "(".$fullname.")";
							}
						}

						$canceledTxn = false;
						$withdrawal_id = $getData->withdrawal_id;

						$where = [ 'id' => $getData->id ];
						$deleting = $wpdb->delete( $tableWithdraw, $where );
						if( $deleting ){
							$whereTxn = [ 'txn_id_ref' => $withdrawal_id ];
							$dataTxn = [ 'status' => -1, 'reason' => $_POST['cancel_withdrawal_request_reason'], 'short_description' => $_POST['cancel_withdrawal_request_reason'] ];
							$updating = $wpdb->update( $tableTransactionHistory, $dataTxn, $whereTxn );
							if( $updating ){
								$canceledTxn = true;
							}
						}

						if( $canceledTxn == true ){
							$html = '<p class="text-center">' . sprintf( __('You have canceled the withdrawal requested on %s by %s %s for %s CSR to <span class="eth_address_mono">%s</span> address.<br/><br/>The reason you provided was %s', CIP_TXTDOMAIN), $requestedDate, $getData->username, $fullname, number_format( $getData->withdraw_amount, 2, '.', ',' ), $getData->eth_address, $_POST['cancel_withdrawal_request_reason'] ) . '</p>';
							$out = array( "error" => 0,'msg' => __('Withdraw canceled',CIP_TXTDOMAIN), 'html' => $html );

							$logs = sprintf( __('Canceled the withdrawal request by %s at %s. withdrawal requested on %s by %s %s for %s CSR to %s address. The reason you provided was %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $requestedDate, $getData->username, $fullname, number_format( $getData->withdraw_amount, 2, '.', ',' ), $getData->eth_address, $_POST['cancel_withdrawal_request_reason'] );
							create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
						}else{

							$logs = sprintf( __('Withdraw cancellation failed. Withdrawal ID: %s', CIP_TXTDOMAIN), $withdrawal_id );
							create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );

							$out = array( "error" => 0,'msg' => __('Withdraw cancellation failed.',CIP_TXTDOMAIN) );
						}

					}
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_approve_withdraw_request_action', 'cip_approve_withdraw_request_action_callback' );
function cip_approve_withdraw_request_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

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

				$decryptedId_raw = base64_decode( $_POST['thisId'] );
				$id = preg_replace(sprintf('/%s/', md5('CIP_WithdrawalRequestApprove_CIP') ), '', $decryptedId_raw);
				if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_WithdrawalRequestApprove_CIP') ) ){
					$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND `id` = ".$id." AND `withdrawal_process_status` = 'Under review'");
					if( $getData ){
						$where = [ 'id' => $getData->id ];
						$update = $wpdb->update( $tableWithdraw, ['withdrawal_process_status' => 'Pending'], $where );
						if( $update ){
							$logs = sprintf( __('Withdrawal request status changed from Under review to Pending on %s by %s.
							Withdraw details: email: %s, username: %s, Withdrawal ID: %s, Withdrawal amount: %s CSR', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $current_user->user_email, $getData->email, $getData->username, $getData->withdrawal_id, $getData->withdraw_amount );
							create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
							$out = array( "error" => 0,'msg' => __('Withdraw request approved',CIP_TXTDOMAIN) );
						}
					}
				}

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_review_withdraw_request_action', 'cip_review_withdraw_request_action_callback' );
function cip_review_withdraw_request_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

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

				$decryptedId_raw = base64_decode( $_POST['thisId'] );
				$id = preg_replace(sprintf('/%s/', md5('CIP_WithdrawalRequestReview_CIP') ), '', $decryptedId_raw);
				if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_WithdrawalRequestReview_CIP') ) ){
					$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND `id` = ".$id." AND ( `withdrawal_process_status` != 'Under review' OR `withdrawal_process_status` IS NULL )");
					if( $getData ){
						$where = [ 'id' => $getData->id ];
						$update = $wpdb->update( $tableWithdraw, ['withdrawal_process_status' => 'Under review'], $where );
						if( $update ){
							$logs = sprintf( __('Withdrawal request status changed from Pending to Under review on %s by %s.
							Withdraw details: email: %s, username: %s, Withdrawal ID: %s, Withdrawal amount: %s CSR', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $current_user->user_email, $getData->email, $getData->username, $getData->withdrawal_id, $getData->withdraw_amount );
							create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
							$out = array( "error" => 0,'msg' => __('Withdraw request Under review',CIP_TXTDOMAIN) );
						}
					}
				}

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
// bulk review withdraw request
add_action( 'wp_ajax_approve_selected_withdraw_request_action', 'approve_selected_withdraw_request_action_callback' );
function approve_selected_withdraw_request_action_callback(){
	
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){

		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;
		if( $ga2fa_delivery_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( !empty( $_POST['user_ga_otp'] ) ){

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

				if( wp_verify_nonce( $_POST['_micro'], 'CIP_WithdrawalRequestApproveSelected_CIP' ) ){

					$selectedWithdrawRequestIdsEncrypt = ( isset( $_POST['selectedWithdrawRequestIds'] ) && !empty( $_POST['selectedWithdrawRequestIds'] ) ) ? $_POST['selectedWithdrawRequestIds'] : array();
					$selectedWithdrawRequestIdsData = array();
					if( !empty( $selectedWithdrawRequestIdsEncrypt ) ){
						$selectedWithdrawRequestIdsEncrypt = explode(',',$selectedWithdrawRequestIdsEncrypt);
						foreach( $selectedWithdrawRequestIdsEncrypt as $encryptId ){
							$decryptedIdRaw = base64_decode( $encryptId );
							$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
							$selectedWithdrawRequestIdsData[] = $decryptedUserId;
						}
					}

					$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
					$filter_qry = "";
					$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
					$filterByUsername = "";
					$filterByValueUsername = "";
					if( !empty( $filterByConditionsUsername ) ){
						$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
						if( $filterByUsername == 'is_exactly_simple' ){
							$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
						}else{
							$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
						}
					}
					$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
					if( $filterByUsername != 'none' ){
						$filters['username'] = $filterByValueUsername;
					}

					$isNumericColumn = array('withdraw_amount', 'withdrawal_fee', 'received_amount');
					$isDateColumn = array('requested_date');

					if( !empty( $filters ) ){
						foreach( $filters as $filterKey => $filterData ){
							if( $filterKey == 'withdrawal_id' ){
								$filter_qry .= " AND `withdrawal_id`='".$filterData."'";
							}else if( $filterKey == 'requested_date' ){
								$dateObject = explode(" - ",$filterData);
								$fromDate = "";
								$toDate = "";
								if( isset( $dateObject[0] ) && isset( $dateObject[1] ) ){
									$fromDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[0]);
									if( $fromDateObj ){
										$fromDate = $fromDateObj->format('Y-m-d');
									}
									$toDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[1]);
									if( $toDateObj ){
										$toDate = $toDateObj->format('Y-m-d');
									}
									if( $fromDate && $toDate ){
										$filter_qry .= " AND (date(`requested_date`) BETWEEN '$fromDate' AND '$toDate')";
									}
								}
							}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
								if( str_contains($filterData, '-') ){ //between
									$filterDataMinMax = explode('-', $filterData);
									$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
								}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
									$filter_qry .= " AND `$filterKey` $filterData";
								}else{
									$filter_qry .= " AND `$filterKey` = " . $filterData . "";
								}
							}else if( $filterKey == 'username' ){
								if( $filterByUsername != 'none' ){
									if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
										$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
									}
								}
							}else if( $filterKey == 'user_star' ){
								if( $filterData == 0 ){
									$filter_qry .= " AND ( `$filterKey` = " . $filterData . " OR `$filterKey` IS NULL OR `$filterKey` = '')";
								}else{
									$filter_qry .= " AND `$filterKey` = " . $filterData . "";
								}
							}else if( $filterKey == 'withdrawal_process_status' ){
								if( $filterData == 'Pending' ){
									$filter_qry .= " AND ( `$filterKey` = '" . $filterData . "' OR `$filterKey` IS NULL OR `$filterKey` = '')";
								}else{
									$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
								}
							}else if( $filterKey == 'token' ){
								$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
							}else{
								$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
							}
						}
						
					}

					$sessionDataQry = "";
					$sessionDataQry = ' AND `id` IN ('. implode(',', $selectedWithdrawRequestIdsData) .')';
			

					$getWithdrawList = $wpdb->get_col("SELECT id FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");

					$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 AND withdrawal_process_status = 'Pending' $filter_qry $sessionDataQry");


					if($total_items <= 0)
					{

						$placeholders = implode(',', $getWithdrawList);

						$sql = $wpdb->prepare("UPDATE {$tableWithdraw} SET withdrawal_process_status = 'Pending' WHERE id IN ($placeholders)");

						$update = $wpdb->query( $sql );

						if( $update ){
							
							$logs = sprintf( __('Bulk Withdrawal request status changed from Under review to Pending on %s by %s.
							Withdraw ids: %s ', CIP_TXTDOMAIN), date_i18n('d/m/Y H:i A'), $current_user->user_email, $placeholders);
							create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
							$out = array( "error" => 0,'msg' => __('Withdraw request moved to pending',CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}

					}
					else{
						$out = array( "error" => 1,'msg' => __('Please select under review request only',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}

			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}

add_action( 'wp_ajax_downloadingCsrWDeliveryRequests', 'downloadingCsrWDeliveryRequests_callback' );
function downloadingCsrWDeliveryRequests_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyDownloadCSRWalletRequestDeliveryyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		global $wpdb;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		/* $sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionWdRequestSelectionData'] ) && !empty( $_SESSION['sessionWdRequestSelectionData'] ) ) ? $_SESSION['sessionWdRequestSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		} */
		$withdrawRequestIdsEncrypt = ( isset( $_POST['withdrawRequestIds'] ) && !empty( $_POST['withdrawRequestIds'] ) ) ? $_POST['withdrawRequestIds'] : array();
		$withdrawRequestIdsData = array();
		if( !empty( $withdrawRequestIdsEncrypt ) ){
			foreach( $withdrawRequestIdsEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDREQUESTSELECTION_PIC') ), '', $decryptedIdRaw);
				$withdrawRequestIdsData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		/* $sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		} */
		$sessionDataQry = "";
		$sessionDataQry = ' AND `id` IN ('. implode(',', $withdrawRequestIdsData) .')';
		$filter_qry = "";

		$filterByConditionsUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
		$filterByUsername = "";
		$filterByValueUsername = "";
		if( !empty( $filterByConditionsUsername ) ){
			$filterByUsername = $filterByConditionsUsername['filter_condition_type_username'];
			if( $filterByUsername == 'is_exactly_simple' ){
				$filterByValueUsername = array_filter( explode(',', $filterByConditionsUsername['filter_condition_value_username_bulk'] ) );
			}else{
				$filterByValueUsername = $filterByConditionsUsername['filter_condition_value_username'];
			}
		}
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );

		if( $filterByUsername != 'none' ){
			$filters['username'] = $filterByValueUsername;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 $sessionDataQry");
		$isNumericColumn = array('withdraw_amount', 'received_amount');
		if( !empty( $filters ) ){

			foreach( $filters as $filterKey => $filterData ){
				if( $filterKey == 'withdrawal_id' ){
					$filter_qry .= " AND `withdrawal_id`='".$filterData."'";
				}else if( $filterKey == 'requested_date' ){

					$dateObject = explode(" - ",$filterData);
					$fromDate = "";
					$toDate = "";
					if( isset( $dateObject[0] ) && isset( $dateObject[1] ) ){
						$fromDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[0]);
						if( $fromDateObj ){
							$fromDate = $fromDateObj->format('Y-m-d');
						}
						$toDateObj = DateTime::createFromFormat('d-m-Y', $dateObject[1]);
						if( $toDateObj ){
							$toDate = $toDateObj->format('Y-m-d');
						}
						if( $fromDate && $toDate ){
							$filter_qry .= " AND (date(`requested_date`) BETWEEN '$fromDate' AND '$toDate')";
						}
					}

				}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
					if( str_contains($filterData, '-') ){ //between
						$filterDataMinMax = explode('-', $filterData);
						$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
					}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
						$filter_qry .= " AND `$filterKey` $filterData";
					}else{
						$filter_qry .= " AND `$filterKey` = " . $filterData . "";
					}
				}else if( $filterKey == 'username' ){
					if( $filterByUsername != 'none' ){
						if( ( $filterByUsername == 'is_exactly' || $filterByUsername == 'is_exactly_simple' ) && !empty( $filterData ) ){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
						}
					}
				}else if( $filterKey == 'withdrawal_process_status' ){
					if( $filterData == 'Pending' ){
						$filter_qry .= " AND ( `$filterKey` = '" . $filterData . "' OR `$filterKey` IS NULL )";
					}else{
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					}
				}else if( $filterKey == 'token' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
		}
		$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1 $filter_qry $sessionDataQry");
		$exportFile = fopen('php://memory', 'w');
		$columnHeader = array( 'withdrawal_id', 'requested_date', 'email', 'star_rank', 'username', 'first_name', 'last_name', 'eth_address', 'withdraw_amount', 'withdrawal_fee', 'received_amount' );
		$newColumnHeader = array();
		if( !empty( $_POST['getVisibleColumns'] ) && is_array( $_POST['getVisibleColumns'] ) ){
			foreach( $_POST['getVisibleColumns'] as $getVisibleColumns ){
				if( in_array( $getVisibleColumns, $columnHeader ) ){
					$newColumnHeader[] = $getVisibleColumns;
				}
			}
		}

		if( in_array( 'withdrawal_process_status', $_POST['getVisibleColumns'] ) ){
			$newColumnHeader[] = 'status';
		}

		fputcsv($exportFile, $newColumnHeader);
		if( $getWithdrawList ){
			foreach( $getWithdrawList as $getWithdraw ){

				$rowData = array();
				if( !empty( $newColumnHeader ) ){
					foreach( $newColumnHeader as $newColumn ){
						if( $newColumn == 'status' ){
							if( empty( $getWithdraw->withdrawal_process_status ) ){
								$rowData[] = 'Pending';
							}else{
								$rowData[] = $getWithdraw->withdrawal_process_status;
							}
						}else{
							$rowData[] = $getWithdraw->$newColumn;
						}
					}
				}
				// $rowData = array( $getWithdraw->withdrawal_id, $getWithdraw->requested_date, $getWithdraw->email, $getWithdraw->user_star, $getWithdraw->username, $getWithdraw->first_name, $getWithdraw->last_name, $getWithdraw->eth_address, $getWithdraw->withdraw_amount, $getWithdraw->withdrawal_fee, $getWithdraw->received_amount );
				fputcsv($exportFile, $rowData);
			}
		}
		$current_user = wp_get_current_user();
		$logs = sprintf( __('CSR Wallet Delivery Requests download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
		fseek($exportFile, 0);
		$file_name = 'CSR-Wallet-Delivery-Request-'.date_i18n('d-m-Y H-i-s');
		header('content-type:application/csv;charset=UTF-8');
		header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
		fpassthru($exportFile);
		fclose($exportFile);
		exit;
	}
	echo wp_json_encode( $out );
	exit;
}
add_filter( 'gform_validation_6', 'user_registration_form_validation' );
function user_registration_form_validation($validation_result){
	$form = $validation_result['form'];

	$login_page_id = get_option( 'login_page_url' );

	$first_name = rgpost('input_1_3');
	$last_name = rgpost('input_1_6');
	$username = trim( ucfirst( $first_name ).ucfirst( $last_name ) );
	$user_email = rgpost('input_3');
	$introduced_by = rgpost('input_30');

	$password = trim( rgpost('input_31') );
	$confirm_password = trim( rgpost('input_33') );
	if( $validation_result['is_valid'] == true ){
		if( email_exists( $user_email ) ){
			$validation_result['is_valid'] = false;
			foreach( $form['fields'] as &$field ) {
				if ( $field->id == '3' ) {
					$field->failed_validation = true;
					$field->validation_message = sprintf( __('You are already registered. <a href="%s">Click here to login</a>', CIP_TXTDOMAIN), get_permalink( $login_page_id ) );
					break;
				}
			}
		}else{
			$foundUser = corsair_get_users_from_sourceapi( $user_email );
			if( $foundUser ){
				$validation_result['is_valid'] = false;
				foreach( $form['fields'] as &$field ) {
					if ( $field->id == '3' ) {
						$field->failed_validation = true;
						$field->validation_message = sprintf( __('You are already registered. <a href="%s">Click here to login</a>', CIP_TXTDOMAIN), get_permalink( $login_page_id ) );
						break;
					}
				}
			}

		}
		if( !empty( $introduced_by ) ){
			if( !corsair_get_users_from_sourceapi_byusername( $introduced_by ) && $_SESSION['introduced_by_error_counter'] != 1 ){
				$_SESSION['introduced_by_error_counter'] = 1;
				$validation_result['is_valid'] = false;
				foreach( $form['fields'] as &$field ) {
					if ( $field->id == '30' ) {
						$field->failed_validation = true;
						$field->validation_message = __('Invalid Introducer ID. Please verify with the person that introduced you to CSRnow.com', CIP_TXTDOMAIN);
						break;
					}
				}
			}
		}
		$number = preg_match( '@[0-9]@', $password );
		$pass_match_error = false;
		if( $password != $confirm_password ){
			$pass_match_error = true;
			$validation_result['is_valid'] = false;
			foreach( $form['fields'] as &$field ){
				if ( $field->id == '31' ) {
					$field->failed_validation = true;
					$field->validation_message = __('Passwords don\'t match.', CIP_TXTDOMAIN);
					break;
				}
			}
		}
		if( !$pass_match_error ){
			$errorOne = false;
			$errorTwo = false;
			if( !$number ){
				$validation_result['is_valid'] = false;
				$pwStrengthMsg = __("must contain at least one number.",CIP_TXTDOMAIN);
				$errorOne = true;
			}
			if( strlen($password) < 8 ){
				$validation_result['is_valid'] = false;
				$pwStrengthMsg = __("must be at least 8 characters.",CIP_TXTDOMAIN);
				$errorTwo = true;
			}
			if( $errorOne && $errorTwo ){
				$validation_result['is_valid'] = false;
				$pwStrengthMsg = __("Password must contain at least one number and must be at least 8 characters.",CIP_TXTDOMAIN);
			}
			if( $validation_result['is_valid'] == false ){
				foreach( $form['fields'] as &$field ){
					if ( $field->id == '31' ) {
						$field->failed_validation = true;
						$field->validation_message = $pwStrengthMsg;
						break;
					}
				}
			}
		}
	}
	$validation_result['form'] = $form;
	return $validation_result;
}
function corsair_get_users_from_sourceapi_byusername($username = '' ){
	$sourceUrl = get_sourse_api_url();
	$result = false;
	if( empty( $sourceUrl ) ){
		return false;
	}

	$request_url = add_query_arg( 'username', urlencode( $username ), $sourceUrl );
	$response = wp_remote_get( $request_url );
	if( is_wp_error( $response ) ) {
		return false;
	}
	$response_body = wp_remote_retrieve_body( $response );
	$data = json_decode( $response_body );
	if( is_object( $data ) && isset( $data->Status ) ){
		$result = true;
	}
	return $result;
}
add_action('gform_after_submission_6', 'gform_user_register_after_success_submit', 10, 2);
function gform_user_register_after_success_submit($entry, $form) {
	global $wpdb;
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_email = $entry[3];
	$business_name = $entry[2];
	$introduced_by = $entry[30];
	$password = $entry[31];
	$first_name = $entry['1.3'];
	$last_name = $entry['1.6'];
	$username = trim( ucfirst( $first_name ).ucfirst( $last_name ) );
	if( empty( $introduced_by ) ){
		$introduced_by = 'amplivo';
	}else if( !corsair_get_users_from_sourceapi_byusername( $introduced_by ) ){
		$introduced_by = 'amplivo';
	}
	$username_counter = 0;
	$newUsername = $username;
	//check in wordpress user
	do{
		$exists_wp = check_username_in_wp($username);
		if( $exists_wp ){
			$username_counter++;
			$username = $newUsername . $username_counter;
		}
	}while($exists_wp);
	//check from amplivo api
	$newUsernameAmplivo = $username;
	do{
		$exists_amplivo = check_username_in_amplivo($username);
		if( $exists_amplivo ){
			$username_counter++;
			$username = $newUsernameAmplivo . $username_counter;
		}
	}while($exists_amplivo);
	// $user_password = wp_generate_password( 12, false );
	$user_password = $password;
	$username = sanitize_user( $username );
	$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 );
			update_user_meta( $user_id, 'first_name', trim( $first_name ) );
            update_user_meta( $user_id, 'last_name', trim( $last_name ) );
			$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 ){
				$logs = sprintf( __('Member user registered. %s. But there was a problem sending verification email to user.', CIP_TXTDOMAIN), $user_email.'('. $username .')' );
				create_cip_logs_entery( 0, 'member', '','member', $logs, true );
			}else{

				$logs = sprintf( __('Member user registered. %s. Verification sent', CIP_TXTDOMAIN), $user_email.'('. $username .')' );
				create_cip_logs_entery( 0, 'member', '','member', $logs, true );
				update_user_meta( $user_id, 'cssetautologin', 1 );
			}
			$getRetirementSetting = $wpdb->get_row("SELECT `id` FROM $tableRetirementSetting WHERE `email` = '".$user_email."' ");
			if( !$getRetirementSetting ){
				$retirementData = array(
					'email'					=>	$user_email,
					'company_name'			=>	$business_name,
					'introduced_by'			=>	$introduced_by,
					'last_update'			=>	date_i18n('Y-m-d H:i:s'),
				);
				$insertRetirementSetting = $wpdb->insert( $tableRetirementSetting, $retirementData );
			}
			/* if( isset($_COOKIE['csr_introducer']) ){
				unset($_COOKIE['csr_introducer']);
				setcookie('csr_introducer', '', -1, '/');
			} */
			unset( $_SESSION['introduced_by_error_counter'] );
			$_SESSION['introduced_by_error_counter'] = "";

		}else{
			$logs = sprintf( __('Member user registration faild. %s', CIP_TXTDOMAIN), $user_email.'('. $username .')' );
			create_cip_logs_entery( 0, 'member', '','member', $logs, true );
		}
	}else{
		$logs = sprintf( __('Member user registration faild. %s', CIP_TXTDOMAIN), $user_email.'('. $username .')' . ' => ' . $user->get_error_message() );
		create_cip_logs_entery( 0, 'member', '','member', $logs, true );
	}
}
add_action( 'init', 'cip_verify_user_registration_email' );
function cip_verify_user_registration_email(){
	if( isset( $_GET['verification_action'] ) && !empty( $_GET['verification_action'] ) ){
		$data = unserialize(base64_decode( $_GET['verification_action'] ));
		$refEmail = rawurldecode( $data['name'] );
		$userEmail = decrypt($refEmail,$data['activation_key'] . "CIP2023CIP");
		$getWpUser = get_user_by( 'email', $userEmail );
		if( is_serialized( base64_decode( $_GET['verification_action'] ) ) ){
			if( !empty( $userEmail ) && $getWpUser ){
				$activation_key = get_user_meta($getWpUser->ID, 'csrmember_activation_key', true);
				if( $activation_key == $data['activation_key'] ){
					update_user_meta( $getWpUser->ID, 'csrmember_activation_status', 1);
					delete_user_meta( $getWpUser->ID, 'csrmember_activation_key' );
					setcookie('email-verification', 'Yes' , 0, "/");
					wp_redirect( get_permalink( get_page_by_path('content/operations/email-verification') ) );
					exit;
				}
			}
		}
	}
}
add_shortcode('Email-Verification-Title', 'email_verification_title_callback');
function email_verification_title_callback(){
	$html = "";
	ob_start();
	if( isset( $_COOKIE['email-verification'] ) && !empty( $_COOKIE['email-verification'] ) && $_COOKIE['email-verification'] == 'Yes' ){
		echo '<h1 class="email-verification-heading">'.__('Registration complete', CIP_TXTDOMAIN).'</h1>';
	}else{
		echo '<h1 class="email-verification-heading">'.__('Email Verification', CIP_TXTDOMAIN).'</h1>';
	}
	$html .= ob_get_clean();
	return $html;
}
add_shortcode('Email-Verification-Error-Msg', 'email_verification_error_msg_callback');
function email_verification_error_msg_callback(){
	$html = "";
	ob_start();
	if( isset( $_COOKIE['email-verification'] ) && !empty( $_COOKIE['email-verification'] ) && $_COOKIE['email-verification'] == 'Yes' ){
		?><p class="email-verification-success"><?php echo __('Thank you for completing your registration with CSRNow.com.', CIP_TXTDOMAIN) ?></p><?php
		setcookie('email-verification', 'verified' , 0, "/");
	}else{
		?>
		<p class="email-verification-error"><?php echo __('Verification url is invalid or expired', CIP_TXTDOMAIN) ?></p>
		<style>.after_email_verified_section{ display:none !important; }</style>
		<?php
	}
	$html .= ob_get_clean();
	return $html;
}
function check_username_in_wp( $username ){
	$exists_wp = false;
	if( username_exists( $username ) ){
		$exists_wp = true;
	}
	return $exists_wp;
}
function check_username_in_amplivo($username = '' ){
	$sourceUrl = get_sourse_api_url();
	$exists_amplivo = false;
	if( empty( $sourceUrl ) ){
		$exists_amplivo = false;
	}

	$request_url = add_query_arg( 'username', urlencode( $username ), $sourceUrl );
	$response = wp_remote_get( $request_url );
	if( is_wp_error( $response ) ) {
		$exists_amplivo = false;
	}
	$response_body = wp_remote_retrieve_body( $response );
	$data = json_decode( $response_body );
	if( is_object( $data ) && isset( $data->Status ) ){
		$exists_amplivo = true;
	}
	return $exists_amplivo;
}
add_action( 'wp_ajax_getValidateAddNewCsrWalletDataAct', 'cip_getValidateAddNewCsrWalletDataAct_callback' );
function cip_getValidateAddNewCsrWalletDataAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$isConfirmResumeDistribution = 0;

	if( wp_verify_nonce( $_POST['_micro'],'_XyValidateAddNewCsrWalletDatayX_' ) ){

		$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

		if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
			$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( wp_verify_nonce( $_POST['isChangeMicro'], $refAccount ) ){ //adding

			$getCsrDataExists = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND ( email != '".$refAccount."' AND email IS NOT NULL AND email <> '') AND `sign_verify` = 1");
			if( $getCsrDataExists ){
				$out = array( "error" => 1, 'msg' => __('Wallet address already in use', CIP_TXTDOMAIN) );
			}else{

				$getCsrDataExists = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE eth_address = '". $_POST['thiseth'] ."' AND email = '".$refAccount."'");
				if( $getCsrDataExists ){
					$out = array( "error" => 1, 'msg' => __('You can not use you own wallet address multiple times.', CIP_TXTDOMAIN) );
				}else{
					$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $_POST['thiseth'], 'isConfirmResumeDistribution' => $isConfirmResumeDistribution );
				}
			}
		}
	}
	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_addNewCsrWalletAddressMemberAct','cip_addNewCsrWalletAddressMemberAct_callback');
function cip_addNewCsrWalletAddressMemberAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$current_user = wp_get_current_user();
	$user_email = $current_user->user_email;
	$username = $current_user->user_login;
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	if( !isset( $_SESSION['refAccount'] ) || $_SESSION['refAccount'] == "" ){
		$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
		echo wp_json_encode( $out );
		exit;
	}
	if( $user_email != $refAccount ){
		$out = array( "error" => 1,'msg' => __('Something went wrong. Please login as member',CIP_TXTDOMAIN) );
		echo wp_json_encode( $out );
		exit;
	}
	if( wp_verify_nonce( $_POST['_micro'], $refAccount ) ){
		if( !empty( $_POST['csrwalletaddress'] ) && ( isset( $_POST['signature'] ) && !empty( $_POST['signature'] ) ) && $_POST['verifyingProcess'] == 'yes' ){ // sign verify
			$message = 'I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] );
			$verified = verifySignature('I '.$refAccount.' confirm that I own the address: '.strtolower( $_POST['csrwalletaddress'] ), $_POST['signature'], strtolower( $_POST['csrwalletaddress'] ));
			if( $verified ){

				$ip_address = cip_get_client_ip();
				$logs = sprintf( __('MetaMask\'s signature & message of %s is signature : %s, message : %s, ip : %s. At %s', CIP_TXTDOMAIN), $refAccount, $_POST['signature'], $message, $ip_address, date_i18n('d/m/Y H:i A') );
				create_cip_logs_entery( 0, 'profile', '','member', $logs, true );
				$first_name = "";
				$last_name = "";

				if( !empty( $current_user->user_firstname ) ){
					$first_name = $current_user->user_firstname;
				}
				if( !empty( $current_user->user_lastname ) ){
					$last_name = $current_user->user_lastname;
				}
				$getTokenHolderData = $wpdb->get_row("SELECT * FROM $tableName WHERE `email` = '".$refAccount."'");
				if( empty( $first_name ) && $getTokenHolderData ){
					$first_name = $getTokenHolderData->first_name;
				}
				if( empty( $last_name ) && $getTokenHolderData ){
					$last_name = $getTokenHolderData->last_name;
				}
				// $checkDirectKyc = $wpdb->get_row("SELECT * FROM $tableName WHERE `email` = '".$refAccount."' AND ( eth_address IS NULL OR eth_address = '' ) AND ( `csr_amount_initial` IS NULL OR `csr_amount_initial` = '' OR `csr_amount_initial` = 0 ) AND ( `csr_amount_issued` IS NULL OR `csr_amount_issued` = '' OR `csr_amount_issued` = 0 ) AND ( `amount_due` IS NULL OR `amount_due` = '' OR `amount_due` = 0 )");
				/* $getUsernameData = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE username = '".$current_user."'");
				$getEmailData = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE email = '".$user_email."' ");
				if( $getUsernameData ){
					$out = array( "error" => 1,'msg' => __('Username in use, please choose another username.',CIP_TXTDOMAIN) );
				}else if( $getEmailData ){
					$out = array( "error" => 1,'msg' => __('Email address in use, please choose another email address.',CIP_TXTDOMAIN) );
				}else{ */
					$insertData = ['username' => $username, 'email' => $user_email, 'first_name' => $first_name, 'last_name' => $last_name, 'eth_address' => $_POST['csrwalletaddress'], 'sign_verify' => 1, 'last_update' => date_i18n('Y-m-d H:i A') ];
					$insert = $wpdb->insert( $tableName, $insertData );
					if( $insert ){
						$insert_id = $wpdb->insert_id;
						$logs = sprintf( __('CSR wallet address (%s) added by Member(%s) at %s', CIP_TXTDOMAIN),$_POST['csrwalletaddress'], $user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( 0, 'profile', '','sa', $logs, true  );
						$out = array( "error" => 0, 'msg' => __('CSR Wallet added successfully', CIP_TXTDOMAIN), 'updateRowCount' => 0, 'html' => '', 'isDirectAdded' => 1 );
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to add CSR wallet address',CIP_TXTDOMAIN) );
					}
				// }
			}else{
				$out = array( "error" => 1, 'msg' => __('Verification failed', CIP_TXTDOMAIN) );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'init', 'set_rewrite_rule_for_introducer_var', 10 );
function set_rewrite_rule_for_introducer_var(){
    add_rewrite_rule( 'introducer/([a-z0-9-]+)[/]?$', 'index.php?introducer=$matches[1]', 'top' );
	if( !session_id() ){ @session_start(); }
}
add_filter( 'query_vars', 'assign_introducer_to_query_variable', 10 );
function assign_introducer_to_query_variable( $query_vars ){
    $query_vars[] = 'introducer';
    return $query_vars;
}
add_action( 'template_redirect', 'set_introducer_to_session', 10 );
function set_introducer_to_session(){
	$introducer_var = get_query_var( 'introducer' );
	if( !empty( $introducer_var ) ){
		if( corsair_get_users_from_sourceapi_byusername( $introducer_var ) ){
			setcookie('csr_introducer', $introducer_var, time() + ( 86400 * 30 ), "/");
		}
		wp_redirect( site_url() );
		exit;
	}
	if (is_page(4258)) {
		global $wpdb;
		$tableScheduler = $wpdb->prefix.'csr_scheduler';
		$amplivo_api_mode = get_option('amplivo_api_mode');
		if ($amplivo_api_mode == 'live') {
			$sourceUrl = get_option('amplivo_api_live_source_url') . 'get-csr-price-changes';
		} else {
			$sourceUrl = get_option('amplivo_api_test_source_url') . 'get-csr-price-changes';
		}
		// $sourceUrl = 'https://cloudhorizon.sandbox.jox.hu/api/get-csr-price-changes';

		// Prepare the request arguments for wp_remote_post()
		$username = get_option( 'amplivo_api_auth_username' );
		$auth_password = get_option( 'amplivo_api_auth_pwd' );

		// $username = 'amplivoapiuser';
		// $auth_password = 'fdlkg948ty89gh498rghuv';


		// Create an array with the request arguments, including Basic Auth in the headers
		$request_args = array(
			'headers' => array(
				'Authorization' => 'Basic ' . base64_encode( $username . ':' . $auth_password ),
				'Content-Type' => 'application/json', // Adjust content type if necessary
			)
		);

		// Make the POST request using wp_remote_post()
		$responseApi = wp_remote_post($sourceUrl, $request_args);

		$response_body = wp_remote_retrieve_body( $responseApi );

		$data = json_decode( $response_body );

		$hall_of_fame_price_type = ( !empty( get_option('hall_of_fame_price_type') ) ) ? get_option('hall_of_fame_price_type') : 'csr' ;
		if($hall_of_fame_price_type == 'csr'){
			$getapiSellingPrice = ( !empty( get_option('selling_price_csr') ) ) ? get_option('selling_price_csr') : 1;
		}else{
			$getapiSellingPrice = ( !empty( get_option('selling_price_csr25') ) ) ? get_option('selling_price_csr25') : 1;
		}

		if(isset($data->result[0]))
		{
			if($data->result[0]->status == 'active')
			{
				$apiSellingPrice = $data->result[0]->csr_price;
			}
			else
			{
				foreach ($data->result as $key => $value) {
					if($value->status == 'active')
					{
						$apiSellingPrice = $value->csr_price;
					}
				}
			}
		}

		$selling_price_csr = $apiSellingPrice;
		if(!empty($selling_price_csr)){
			if($getapiSellingPrice != $selling_price_csr){
				// update_option( 'selling_price_csr', $selling_price_csr );
				// $status = ( $_POST['price_type'] == 'prompt' ) ? 'active' : 'pending';

				// $schedule_time = ( $_POST['price_type'] == 'prompt' ) ? gmdate('Y-m-d H:i') : sprintf( '%s %s:%s', $_POST['schedule_time_alt'], $_POST['schedule_hours'], $_POST['schedule_minutes'] );

				$data = array(

					'csr_price'		=>	$selling_price_csr,

					'price_type'	=>	'prompt',

					'create_date'	=>	gmdate('Y-m-d H:i'),

					'start_date'	=>	gmdate('Y-m-d H:i'),

					'status'		=>	'active',

				);

				$insert = $wpdb->insert($tableScheduler, $data);

				if( $insert ){

					// if( $_POST['price_type'] == 'prompt' ){

					$lastid = $wpdb->insert_id;

					$getOldActive = $wpdb->get_results("SELECT * FROM $tableScheduler WHERE status='active' AND id!=$lastid");

					if( $getOldActive ){

						foreach( $getOldActive as $oldActive ){

							$dataActive = array( 'status'	=>	'overwritten' );

							$whereActive = array( 'id'	=>	$oldActive->id );

							$updateActive = $wpdb->update($tableScheduler, $dataActive, $whereActive);

						}

					}

					update_option( 'selling_price_csr', $selling_price_csr );
					update_option( 'selling_price_csr25', $selling_price_csr );

				}
			}

		}
	}
}
add_filter( 'gform_replace_merge_tags', 'cip_user_registration_merge_tags_replace_cb', 10, 7 );
function cip_user_registration_merge_tags_replace_cb( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {
	$introducedby = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '';
	$custom_merge_tags = array();
	if( $form['id'] == 6 && !empty( $introducedby ) ){
		$custom_merge_tags = array(
			'{cip_introducedby}' 	=> $introducedby,
		);
	}
    return str_replace( array_keys( $custom_merge_tags ), array_values( $custom_merge_tags ), $text);
}
add_filter('gform_field_content', 'cip_user_registration_field_content_replacebyvalue_cb', 999, 5);
function cip_user_registration_field_content_replacebyvalue_cb($field_content, $field, $value, $lead_id, $form_id) {

	if( $form_id == 6 ){
		$introducedby = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '';
		if( strpos($field_content, '{cip_introducedby}') !== false && !empty( $introducedby ) ){
			$field_content = str_replace('{cip_introducedby}', $introducedby, $field_content);
		}
	}
	if( $form_id == 6 &&  $field->id == 30 ){
		$field_content = str_replace  ( $field->label, $field->label. ' <span class="fa fa-info-circle" data-toggle-column="tooltip" data-placement="top" title="Please ask the person who introduced you to CSRnow.com for their Introducer ID."></span>', $field_content );
	}
	return $field_content;
}
add_filter( 'gform_pre_render_6', 'set_user_registration_gform_field_value_default', 10, 3 );
function set_user_registration_gform_field_value_default( $form, $ajax , $field_values ) {
	$introducedby = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '';
	$fields = $form['fields'];
	foreach( $fields as &$field ){
		if ( $field->id == 30 ) {
			$field->defaultValue = $introducedby;
		}
    }
	return $form;
}
add_filter( 'gform_field_css_class_6', 'user_registration_grom_noneditable', 10, 3 );
function user_registration_grom_noneditable( $classes, $field, $form ){
	$readOnlyClass="";
	if( $form['id'] == 6 ){
		$csr_introducer = ( isset( $_COOKIE['csr_introducer'] ) && !empty( $_COOKIE['csr_introducer'] ) ) ? $_COOKIE['csr_introducer'] : '' ;
		if( !empty( $csr_introducer ) ){
			if( $field->id == 30 ){
				$readOnlyClass = ' readField';
			}
		}
		$classes .= $readOnlyClass;
	}
    return $classes;
}
add_filter( 'gform_field_content', function( $content, $field, $value, $lead_id, $form_id ) {
	if( $form_id == 6 ){
		if ( $field->id == 31 || $field->id == 33 ) {
			$autocomplete = 'password';
			return preg_replace( '/<(input|textarea)/', '<${1} autocomplete="' . $autocomplete . '" ', $content );
		}
	}
	return $content;
}, 15, 5 );
add_action('wp_ajax_cip_csr_withdrawals_report_amount_settings_act','cip_csr_withdrawals_report_amount_settings_act_cb');
function cip_csr_withdrawals_report_amount_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxcsrWithdrawalsReportAmountxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){

		$userCancelWithdrawalSwitch = ( !empty( get_option('csr_user_cancel_withdrawal_switch_stop') ) ) ? get_option('csr_user_cancel_withdrawal_switch_stop') : 0;
		$csr_withdrawals_report_amount = ( !empty( get_option('csr_withdrawals_report_amount') ) ) ? get_option('csr_withdrawals_report_amount') : 50000;

		$newValue = ( $_POST['user_cancel_withdrawal_switch'] == 1 ) ? 1 : 0;
		$cancelSwitchText = ( $newValue == 1 ) ? 'Enable' : 'Disable';
		
		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$valueData = array();
		$valueData[] = sprintf( __('Setting saved by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
		$valueData[] = sprintf( __('IP : %s', CIP_TXTDOMAIN), $current_ip );
		$valueData[] = date_i18n('d/m/Y H:i:s');
		$valueData[] = sprintf( __('User : %s', CIP_TXTDOMAIN), get_current_user_id() );
		$valueData[] = __('***Old Values***');

		$valueData[] = sprintf( __('CSR Withdrawals Report Amount : %s', CIP_TXTDOMAIN), $csr_withdrawals_report_amount );
		$valueData[] = sprintf( __('CSR withdrawals cancel switch for user : %s', CIP_TXTDOMAIN), ($userCancelWithdrawalSwitch == 1) ? 'Enable' : 'Disable' );

		$valueData[] = __('***Updated Values***');

		update_option( 'csr_user_cancel_withdrawal_switch_stop', $newValue );
		update_option( 'csr_withdrawals_report_amount', $_POST['csr_withdrawals_report_amount'] );
		
		$valueData[] = sprintf( __('CSR Withdrawals Report Amount : %s', CIP_TXTDOMAIN), $_POST['csr_withdrawals_report_amount'] );
		$valueData[] = sprintf( __('CSR withdrawals cancel switch for user : %s', CIP_TXTDOMAIN), $cancelSwitchText );		

		$message = implode( PHP_EOL, $valueData);

		$filename = 'cip_wallet_option.log';
		$file = fopen(CIP_PLUGIN_BASE.'/'.$filename,"a"); 
		$message = implode( PHP_EOL, $valueData);
		fwrite($file, $message . PHP_EOL); 
		fclose($file);

		$logs = $message;		
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );
		
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_usercancelwithdrawalswitch_settings_act','cip_usercancelwithdrawalswitch_settings_act_cb');
function cip_usercancelwithdrawalswitch_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxUserCancelWithdrawalSwitchxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		
		$current_ip = cip_get_client_ip();
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$userCancelWithdrawalSwitch = ( !empty( get_option('csr_user_cancel_withdrawal_switch_stop') ) ) ? get_option('csr_user_cancel_withdrawal_switch_stop') : 0;
		$newValue = ( $_POST['user_cancel_withdrawal_switch'] == 1 ) ? 1 : 0;
		update_option( 'csr_user_cancel_withdrawal_switch_stop', $newValue );
		$cancelSwitchText = ( $newValue == 1 ) ? 'Enable' : 'Disable';
		
		$logs = sprintf( __('CSR withdrawals cancel switch for user is %s by %s at %s'), $cancelSwitchText, $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $user_id, 'setting_option', '','sm', $logs, true );
		
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('admin_post_withdrawals_report_details_download_act','cip_withdrawals_report_details_download_act_callback');
function cip_withdrawals_report_details_download_act_callback(){
	global $wpdb;
	$csr_withdrawals_report_amount = ( !empty( get_option('csr_withdrawals_report_amount') ) ) ? get_option('csr_withdrawals_report_amount') : 50000;
	$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
	$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1 AND `withdraw_amount` > $csr_withdrawals_report_amount ORDER BY `id` DESC");

	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'email', 'username', 'full name', 'CSR amount' );

	fputcsv($exportFile, $columnHeader);
	$weekNumber = "";
	foreach( $getWithdrawList as $getWithdraw ){
		$full_name = trim( $getWithdraw->first_name.' ' . $getWithdraw->last_name );
		$rowData = array( $getWithdraw->email, $getWithdraw->username, $full_name, $getWithdraw->withdraw_amount );
		fputcsv($exportFile, $rowData);
	}
	$current_user = wp_get_current_user();
	$logs = sprintf( __('CSR Withdrawals Report Over '. $csr_withdrawals_report_amount .' download by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	fseek($exportFile, 0);
	$file_name = 'CSR Withdrawals Report Over '.$csr_withdrawals_report_amount;
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}
add_action( 'wp_ajax_user_cancel_pending_withdraw_request_action', 'cip_user_cancel_pending_withdraw_request_action_callback' );
function cip_user_cancel_pending_withdraw_request_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'member' ) ){
		global $wpdb;

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
		$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_UserWithdrawalRequestCancel_CIP') ), '', $decryptedId_raw);
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_withdrawal = get_user_meta( $user_id, 'google_auth_key_withdrawal', true );
		$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_withdrawal == 1 ) ? 1 : 0;
		$withdrawal_request_wizard_process_user = get_option('withdrawal_request_wizard_process_user');
		$userCancelWithdrawalSwitch = get_option('csr_user_cancel_withdrawal_switch_stop');
		if( !empty( $withdrawal_request_wizard_process_user ) || $userCancelWithdrawalSwitch == 1 ){
			$out = array( "error" => 1,'msg' => __('Cancellations temporarily suspended',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( $corsair_2fa_ga != 'yes' || $ga2fa_login_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_UserWithdrawalRequestCancel_CIP') ) ){
			// $refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
			$refAccount = $current_user->user_email;
			$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
			$getPendingData = $wpdb->get_row("SELECT * FROM $tableTransactionHistory WHERE 1 AND `id` = ".$id." AND $whereEmail AND `status`=0");
			if( $getPendingData ){
				$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND `withdrawal_id`='".$getPendingData->txn_id."' AND `email`='". $getPendingData->email ."' AND `eth_address`='". $getPendingData->eth_address ."' AND `status`=0");

				if( $getData ){

					$requestedDate = "";
					$requestedDateObj = DateTime::createFromFormat('Y-m-d H:i:s', $getData->requested_date);
					if( $requestedDateObj ){
						$requestedDate = $requestedDateObj->format('d/m/Y H:i');
					}

					$fullname = "";
					if( !empty( $getData->first_name ) || !empty( $getData->last_name ) ){
						$fullname = trim( $getData->first_name . ' ' . $getData->last_name );
						if( !empty( $fullname ) ){
							$fullname = "(".$fullname.")";
						}
					}

					$total_step = 3;
					ob_start();
					?>
					<div class="container-fluid">
						<span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>
						<div class="row justify-content-center">
							<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 text-center p-0 mt-2 mb-2">
								<div class="card">
									<form name="cancelPendingWithdrawRequestUserFrm" class="cancelPendingWithdrawRequestUserFrm" id="msform">
										<!-- progressbar -->
										<ul id="progressbar">
											<li class="active" id="fieldmapping"><strong><?php _e('Cancel Withdrawal',CIP_TXTDOMAIN) ?></strong></li>
											<li id="fieldmapping"><strong><?php _e('Confirmation',CIP_TXTDOMAIN) ?></strong></li>
											<li id="fieldmapping"><strong><?php _e('Canceled',CIP_TXTDOMAIN) ?></strong></li>
										</ul>
										<div class="progress">
											<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
										</div>
										<br> <!-- fieldsets -->
										<fieldset class="step_0">
											<div class="form-card">
												<div class="row">
													<div class="col-12">
														<p class="steps"><?php echo sprintf('Step %s - %s', 1, $total_step); ?></p>
													</div>
												</div>

												<div class="row text-center align-items-center pb-0">
												<div class="col-12">
													<?php /*<p><?php echo sprintf( __('You are canceling a withdrawal requested on %s by %s %s for %s CSR to <span class="eth_address_mono">%s</span> address.', CIP_TXTDOMAIN), $requestedDate, $getData->username, $fullname, number_format( $getData->withdraw_amount, 2, '.', '' ), $getData->eth_address ); ?></p>*/ ?>
													<p><?php echo sprintf( __('You are canceling a withdrawal requested on %s for %s CSR to <span class="eth_address_mono">%s</span> address.', CIP_TXTDOMAIN), $requestedDate, number_format( $getData->withdraw_amount, 2, '.', '' ), $getData->eth_address ); ?></p>

													<p><?php _e('You should only cancel a withdrawal request with good reason.', CIP_TXTDOMAIN); ?></p>

												</div>
												<div class="col-3"></div>
												<div class="col-6 form-group">
													<label for="cancel_withdrawal_request_reason"><?php _e('Enter the reason for canceling the withdrawal below.', CIP_TXTDOMAIN); ?></label>
													<textarea class="form-control" id="cancel_withdrawal_request_reason" name="cancel_withdrawal_request_reason"></textarea>
												</div>
												<div class="col-3"></div>
												</div>

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

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

												<div class="row text-center justify-content-center">
													<div class="otp_section pb-3">
														<label for="user_ga_otp_cancel"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
														<input type="text" name="user_ga_otp_cancel" id="user_ga_otp_cancel" class="input mb-1" maxlength="6" pattern="{0-9}+" />
														<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
													</div>
												</div>

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

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

												<div class="row align-items-center pb-5 cancel_withdraw_request_respose_section"></div>

											</div>
											<input type="button" name="previous" class="action-button-previous close_cancel_pending_withdraw_request_user" value="Close" />
										</fieldset>
										<input type="hidden" name="action" value="cancelPendingWithdrawRequestUserAct" />
										<input type="hidden" name="thisId" value="<?php echo $_POST['thisId'] ?>" />
										<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
									</form>
								</div>
							</div>
						</div>
					</div>
					<?php
					$html = ob_get_clean();
					$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancelPendingWithdrawRequestUserAct', 'cip_cancelPendingWithdrawRequestUserAct_callback' );
function cip_cancelPendingWithdrawRequestUserAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'member' ) ){
		global $wpdb;

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_withdrawal = get_user_meta( $user_id, 'google_auth_key_withdrawal', true );
		$ga2fa_login_enabled = ( !empty( $google_auth_key ) && $google_auth_key_withdrawal == 1 ) ? 1 : 0;
		$withdrawal_request_wizard_process_user = get_option('withdrawal_request_wizard_process_user');
		$userCancelWithdrawalSwitch = get_option('csr_user_cancel_withdrawal_switch_stop');
		if( !empty( $withdrawal_request_wizard_process_user ) || $userCancelWithdrawalSwitch == 1 ){
			$out = array( "error" => 1,'msg' => __('Cancellations temporarily suspended',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		if( $corsair_2fa_ga != 'yes' || $ga2fa_login_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( empty( $_POST['cancel_withdrawal_request_reason'] ) ){
			$out = array( "error" => 1,'msg' => __('Please enter reason for canceling the withdrawal',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		// $refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
		$refAccount = $current_user->user_email;
		$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
		if( !empty( $_POST['user_ga_otp_cancel'] ) ){
			$google2fa = new \PragmaRX\Google2FA\Google2FA();
			if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp_cancel'], 0) ){

				$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
				$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

				$decryptedId_raw = base64_decode( $_POST['thisId'] );
				$id = preg_replace(sprintf('/%s/', md5('CIP_UserWithdrawalRequestCancel_CIP') ), '', $decryptedId_raw);

				if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_UserWithdrawalRequestCancel_CIP') ) ){
					$getPendingData = $wpdb->get_row("SELECT * FROM $tableTransactionHistory WHERE 1 AND `id` = ".$id." AND $whereEmail AND `status`=0");
					if( $getPendingData ){
						$getData = $wpdb->get_row("SELECT * FROM $tableWithdraw WHERE 1 AND `withdrawal_id`='".$getPendingData->txn_id."' AND `email`='". $getPendingData->email ."' AND `eth_address`='". $getPendingData->eth_address ."' AND `status`=0");
						if( $getData ){

							$requestedDate = "";
							$requestedDateObj = DateTime::createFromFormat('Y-m-d H:i:s', $getData->requested_date);
							if( $requestedDateObj ){
								$requestedDate = $requestedDateObj->format('d/m/Y H:i');
							}

							$fullname = "";
							if( !empty( $getData->first_name ) || !empty( $getData->last_name ) ){
								$fullname = trim( $getData->first_name . ' ' . $getData->last_name );
								if( !empty( $fullname ) ){
									$fullname = "(".$fullname.")";
								}
							}

							$canceledTxn = false;
							$withdrawal_id = $getData->withdrawal_id;

							$where = [ 'id' => $getData->id ];
							$deleting = $wpdb->delete( $tableWithdraw, $where );
							if( $deleting ){
								$whereTxn = [ 'txn_id_ref' => $withdrawal_id ];
								$dataTxn = [ 'status' => -1, 'reason' => $_POST['cancel_withdrawal_request_reason'], 'short_description' => $_POST['cancel_withdrawal_request_reason'] ];
								$updating = $wpdb->update( $tableTransactionHistory, $dataTxn, $whereTxn );
								if( $updating ){
									$canceledTxn = true;
								}
							}

							if( $canceledTxn == true ){

								$html = '<p class="text-center">' . sprintf( __('You have canceled the withdrawal requested on %s for %s CSR to <span class="eth_address_mono">%s</span> address.<br/><br/>The reason you provided was %s', CIP_TXTDOMAIN), $requestedDate, number_format( $getData->withdraw_amount, 2, '.', ',' ), $getData->eth_address, $_POST['cancel_withdrawal_request_reason'] ) . '</p>';

								$out = array( "error" => 0,'msg' => __('Withdraw canceled',CIP_TXTDOMAIN), 'html' => $html );

								$logs = sprintf( __('Canceled the withdrawal request by %s(member) at %s. withdrawal requested on %s for %s CSR to %s address. The reason you provided was %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $requestedDate, number_format( $getData->withdraw_amount, 2, '.', ',' ), $getData->eth_address, $_POST['cancel_withdrawal_request_reason'] );
								create_cip_logs_entery( $current_user->ID, 'cancel_withdrawal', '','member', $logs, true );
							}else{

								$logs = sprintf( __('Withdraw cancellation failed. by %s at %s. Withdrawal ID: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $withdrawal_id );
								create_cip_logs_entery( $current_user->ID, 'cancel_withdrawal', '','member', $logs, true );

								$out = array( "error" => 0,'msg' => __('Withdraw cancellation failed.',CIP_TXTDOMAIN) );
							}

						}
					}
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_pool_ref_fetch_act', 'cip_pool_ref_fetch_act_callback' );
function cip_pool_ref_fetch_act_callback(){
	global $wpdb;
	$out = array();
	$tableName = $wpdb->prefix.'token_holder';
	$get_pool_refs = $wpdb->get_results("SELECT DISTINCT `pool_ref` FROM $tableName WHERE `pool_ref` like '".$_REQUEST['search']."%'");
	if( $get_pool_refs ){
		foreach( $get_pool_refs as $get_pool_ref ){
			$out[] = array(
				'id'	=>	$get_pool_ref->pool_ref,
				'text'	=>	$get_pool_ref->pool_ref,
			);
		}
	}
	echo wp_json_encode( array( 'results' => $out ) );
	exit;
}
add_action('wp_ajax_cip_weekly_bonus_pool_split_act','cip_weekly_bonus_pool_split_act_callback');
function cip_weekly_bonus_pool_split_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN), 'msg2' => __('Something went wrong.',CIP_TXTDOMAIN) );
	// require 'guzzle/vendor/autoload.php';
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxYSMWeeklyBonusPoolSplitMSYxCIP_' ) ){
		global $table_prefix, $wpdb;
		$thTable = $table_prefix . 'token_holder';
		$tableDistribution = $wpdb->prefix.'token_holder_distribution';
		$tableTemp = $wpdb->prefix.'token_holder_distribution_temp';
		if( ( isset( $_POST['fieldmapping_pool_record'] ) && $_POST['fieldmapping_pool_record'] == 'yes' ) ){ // field mapping
			$delete = $wpdb->query("TRUNCATE TABLE `".$tableDistribution."`");
			$deleteTemp = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
			$new_total_line = 0;
			if( !empty( $_POST['bonus_pool_ref'] ) && is_array( $_POST['bonus_pool_ref'] ) ){
				$getPoolsRecords = $wpdb->get_results('SELECT * FROM `'.$thTable.'` WHERE `pool_ref` IN ("' . implode('", "', $_POST['bonus_pool_ref']) . '")');
				if( $getPoolsRecords ){
					$rowCounter = 0;
					foreach( $getPoolsRecords as $getPoolsRecord){

						$reference = $getPoolsRecord->reference;
						$member_status = $getPoolsRecord->_user_status;
						$eth_address = $getPoolsRecord->eth_address;
						$username = $getPoolsRecord->username;
						$csr_amount_initial = intval( $getPoolsRecord->csr_amount_initial );
						$pool_reference = $getPoolsRecord->pool_ref;

						$validationError = [];
						if( !filter_var($getPoolsRecord->email, FILTER_VALIDATE_EMAIL) ){
							$rowError = true;
							$validationError[] = __('Email is invalid ',CIP_TXTDOMAIN);
						}
						if( empty( $getPoolsRecord->username ) ){
							$rowError = true;
							$validationError[] = __('Username is empty',CIP_TXTDOMAIN);
						}

						if( $csr_amount_initial == "" && $csr_amount_initial < 0 ){
							$rowError = true;
							$validationError[] = __('csr_initial is empty',CIP_TXTDOMAIN);
						}
						if( !is_int( $csr_amount_initial ) ){
							$rowError = true;
							$validationError[] = __('csr_initial is invalid',CIP_TXTDOMAIN);
						}
						if( empty( $getPoolsRecord->text_10 ) ){
							$rowError = true;
							$validationError[] = __('Distribution week is empty',CIP_TXTDOMAIN);
						}
						$distributionWeekPattern  = "/^[0-9]{4}\/[0-9]{2}$/i";
						if( !preg_match($distributionWeekPattern, $getPoolsRecord->text_10) ){
							$rowError = true;
							$validationError[] = __('Not valid format of distribution week',CIP_TXTDOMAIN);
						}
						/* $poolReferencePattern  = "/^Week-[0-9]{2}-of-[0-9]{4}$/i";
						if( !preg_match($poolReferencePattern, $getPoolsRecord->pool_ref) ){
							$rowError = true;
							$validationError[] = __('Not valid format of pool reference',CIP_TXTDOMAIN);
						} */

						$referencePattern  = "/^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$/i";
						if( empty( $getPoolsRecord->reference ) || !preg_match( $referencePattern, $getPoolsRecord->reference ) ){
							$rowError = true;
							$validationError[] = __('Reference is empty or invalid format',CIP_TXTDOMAIN);
						}
						if( !empty( $getPoolsRecord->eth_address ) && AddressValidator::isValid( $getPoolsRecord->eth_address ) !== AddressValidator::ADDRESS_VALID ){
							$rowError = true;
							$validationError[] = __('Address is invalid',CIP_TXTDOMAIN);
						}
						/* if( $member_status != 'active' && $member_status != 'abandoned' ){
							$rowError = true;
							$validationError[] = sprintf( __('found invalid member status `%s`',CIP_TXTDOMAIN), $member_status );
						} */
						if( $rowError === true ){
							$log_msg = 'Row :: ' . $reference . ' :: failed : ' . implode(', ', $validationError).'<br/>';
							$countError++;
							$error = 1;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s',CIP_TXTDOMAIN), $log_msg ), 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
						$rowCounter++;


						$pool_reference_data = explode( "/", $getPoolsRecord->text_10 );
						$yearNumber = $pool_reference_data[0];
						$weekNumber = $pool_reference_data[1];
						/* $weekPos = stripos( $pool_reference, "-" );
						$weekNumber = mb_substr( $pool_reference, $weekPos+1, 2 );

						$yearPos = strripos( $pool_reference, "-" );
						$yearNumber = mb_substr( $pool_reference, $yearPos+1, 4 ); */
						$csr_segmentation = 100;
						if( isset( $_POST['csr_segmentation'] ) && $_POST['csr_segmentation'] >= 10 ){
							$csr_segmentation = $_POST['csr_segmentation'];
						}
						$distribution_status = "";
						if( $eth_address != "") {
							$distribution_status = $getPoolsRecord->corp_approved;
						}else{
							$distribution_status = 'Pending';
						}
						/* if( $eth_address != "") {
							$security_hold_check = $wpdb->get_row("SELECT id,corp_approved FROM $thTable WHERE `eth_address` = '".$eth_address."' AND `username` = '".$username."' AND ( `corp_approved` = 'Security Hold' OR `corp_approved` = 'Hold' )");
							if( $security_hold_check ){
								$distribution_status = $security_hold_check->corp_approved;
							}
						}else if( empty( $eth_address ) ){
							// $distribution_status = 'Missing CSR address';
							$distribution_status = 'Pending';
						} */

						$data = [
							'username'					=>	wp_strip_all_tags( $username ),
							'reference'					=>	wp_strip_all_tags( $reference ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'first_name'				=>	wp_strip_all_tags( $getPoolsRecord->first_name ),
							'last_name'					=>	wp_strip_all_tags( $getPoolsRecord->last_name ),
							// 'created'					=>	date_i18n('d/m/Y'),
							'created'					=>	$getPoolsRecord->redemption_date,
							'email'						=>	wp_strip_all_tags( $getPoolsRecord->email ),
							'csr_amount_issued'			=>	$getPoolsRecord->csr_amount_issued,
							'amount_due'				=>	0,
							'distribution_status'		=>	$distribution_status,
							'member_status'				=>	$member_status,
							'pool_ref'					=>	$pool_reference,
							// 'source'					=>	$source,
							'week_number'				=>	$weekNumber,
							'year_number'				=>	$yearNumber,
							'csr_segmentation'			=>	$csr_segmentation,
							'import_by'					=>	get_current_user_id(),
							'import_date'				=>	date_i18n( 'Y-m-d H:i:s' ),
						];
						$inserting = $wpdb->insert( $tableTemp, $data );
						if( $inserting ){
							$countSuccess++;
						}else{
							$error = 1;
							$countError++;
							$errorText = $wpdb->last_error;
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $rowCounter ) ), 'totalCount' => $total_line, 'msg2' => $errorText );
							echo wp_json_encode( $out );
							exit;
						}

					}
					$totalMsg = sprintf( __('%s record\'s found to process', CIP_TXTDOMAIN),$rowCounter );
					$out = array( "error" => 0,'msg' => $totalMsg, 'msg2' => $totalMsg, 'total_line' => $rowCounter, 'totalmsg' => $totalMsg );
					echo wp_json_encode( $out );
					exit;
				}else{
					$out = array( "error" => 1,'msg' => __('No records found',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}else{
				$out = array( "error" => 1,'msg' => __('Please choose pool reference',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}else if( isset( $_POST['splitting_bonus_start'] ) && $_POST['splitting_bonus_start'] == 'yes' ){ //splitting bonus start
			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTemp WHERE 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );
			$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Splitting 10% distributions started...',CIP_TXTDOMAIN), 'msg2' => __('Splitting 10% distributions started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to process', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset( $_POST['splitting_bonus_data'] ) && $_POST['splitting_bonus_data'] == 'yes' ){ // splitting bonus data loop

			global $table_prefix, $wpdb;
			$tableTemp = $table_prefix.'token_holder_distribution_temp';
			$thdTable = $table_prefix . 'token_holder_distribution';
			$thTable = $table_prefix . 'token_holder';
			//==================================================//

			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;

			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCount = 0;

			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableTemp WHERE 1 LIMIT ".$per_page." OFFSET ".$paged."");
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					$pool_reference = $getTempData->pool_ref;
					$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
					$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
					$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
					$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? str_replace( ',', '', $getTempData->csr_amount_initial) : 0;
					$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
					$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
					$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
					$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
					// $source = ( $getTempData->source != "" ) ? $getTempData->source : '';
					$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
					$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
					$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
					$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
					$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';

					$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
					$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';
					if( $csr_amount_initial <= $csr_segmentation ){
						$admNo = $reference.'-000';
						$newAdmNo = ++$admNo;
						$amount_due = $csr_amount_initial;
						if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
							$corp_approved_10 = $distribution_status;
						}else{
							$corp_approved_10 = 'Pending';
						}
						$notes_external_10 = '| Pending 10% distribution. |';
						if( $distribution_status == 'Security Hold' ){
							$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
						}
						$notes_external_10 = notes_trim_pipe( $notes_external_10 );
						$data = [
							'username'					=>	wp_strip_all_tags( $username ),
							'reference'					=>	wp_strip_all_tags( $newAdmNo ),
							'eth_address'				=>	wp_strip_all_tags( $eth_address ),
							'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
							'first_name'				=>	wp_strip_all_tags( $first_name ),
							'last_name'					=>	wp_strip_all_tags( $last_name ),
							'created'					=>	$created,
							'email'						=>	wp_strip_all_tags( $email ),
							'csr_amount_issued'			=>	0,
							'amount_due'				=>	$amount_due,
							'distribution_status'		=>	$distribution_status,
							'member_status'				=>	$member_status,
							'corp_approved'				=>	$corp_approved_10,
							'notes_external'			=>	$notes_external_10,
							'pool_ref'					=>	$pool_reference,
							'source'					=>	$source,
							'week_number'				=>	$year_number.'/'.$week_number,
							'csr_segmentation'			=>	$csr_segmentation,
							'import_by'					=>	$import_by,
							'import_date'				=>	$import_date,
							'parent_reference'			=>	$reference,
						];
						$inserting = $wpdb->insert( $thdTable, $data );
						if( $inserting ){
							$countSuccess++;
						}else{
							$error = 1;
							$countError++;
							$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
							$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
							echo wp_json_encode( $out );
							exit;
						}
					}else{
						$csr_amount_pending = $csr_amount_initial;
						$totalNumberWeek = 52;

						for( $i=0; $i < 10; $i++ ){

							$amount_due = $csr_amount_pending / ( 10 - $i );
							$amount_due = ceil( $amount_due );
							//$csr_amount_pending = $csr_amount_pending - $amount_due;

							if( $i == 0 ){
								$admNo = $reference.'-000';
							}else{
								$admNo = $newAdmNo;
							}
							$newAdmNo = ++$admNo;

							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| Pending 10% distribution. |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );
							if( $week_number > $totalNumberWeek ){
								$week_number = $week_number - $totalNumberWeek;
								$year_number = $year_number + 1;
							}else{
								$year_number = $year_number;
							}
							$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);

							$data = [
								'username'					=>	wp_strip_all_tags( $username ),
								'reference'					=>	wp_strip_all_tags( $newAdmNo ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'		=>	$csr_amount_initial,
								// 'csr_amount_initial'		=>	$csr_amount_pending,
								'first_name'				=>	wp_strip_all_tags( $first_name ),
								'last_name'					=>	wp_strip_all_tags( $last_name ),
								'created'					=>	$created,
								'email'						=>	wp_strip_all_tags( $email ),
								'csr_amount_issued'			=>	0,
								'amount_due'				=>	$amount_due,
								'distribution_status'		=>	$distribution_status,
								'member_status'				=>	$member_status,
								'corp_approved'				=>	$corp_approved_10,
								'notes_external'			=>	$notes_external_10,
								'pool_ref'					=>	$pool_reference,
								'source'					=>	$source,
								'week_number'				=>	$new_week_number,
								'csr_segmentation'			=>	$csr_segmentation,
								'import_by'					=>	$import_by,
								'import_date'				=>	$import_date,
								'parent_reference'			=>	$reference,
							];

							$csr_amount_pending = $csr_amount_pending - $amount_due;
							$inserting = $wpdb->insert( $thdTable, $data );
							if( $inserting ){
								$countSuccess++;
							}else{
								$error = 1;
								$countError++;
								$delete = $wpdb->query("TRUNCATE TABLE `".$thdTable."`");
								$delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN) );
								echo wp_json_encode( $out );
								exit;
							}
							// $week_number++;
							$week_number = $week_number + 4;

						}
					}
					$rowDataCount = $getTempData->id;
				}
				$getProceedCount = $wpdb->get_var("SELECT COUNT(id) FROM $thdTable WHERE 1");
				$importNoticeMsg = sprintf( __('%s row proceed, %s records inserted<br/>', CIP_TXTDOMAIN), $rowDataCount, $getProceedCount );
				// $msg2 = sprintf( __('%s row splitting process complete',CIP_TXTDOMAIN), getOrdinal( $splitting_id ) );
				$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $rowDataCount );
			}

		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_append_new_bonus_csr_holders_data_act', 'cip_append_new_bonus_csr_holders_data_act_callback' );
function cip_append_new_bonus_csr_holders_data_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYAppendNewBonus_csr_HoldersDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableTempName = $wpdb->prefix.'token_holder_distribution_temp';
		$tableTemp = $wpdb->prefix.'token_holder_distribution_temp';
		$tableName = $wpdb->prefix.'token_holder_distribution';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		if( isset( $_POST['get_append_bonus_data'] ) && $_POST['get_append_bonus_data'] == 'yes' ){

			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTempName WHERE 1 AND `append_status` != 1");
			$per_page = 100;
			$total_paged = ceil( $total_items / $per_page );

			$statusUpdate = $wpdb->query( $wpdb->prepare( "UPDATE $tableName SET `append_status` = %d", 1 ) );
			if( $statusUpdate ){
			}

			$out = array( "error" => 0, 'total_items' => $total_items, 'total_paged' => $total_paged,'msg' => __('Appending 10% distributions started...',CIP_TXTDOMAIN), 'msg2' => __('Appending 10% distributions started...',CIP_TXTDOMAIN), 'totalmsg' => sprintf( __('%s row\'s to append', CIP_TXTDOMAIN),$total_items ) );
		}else if( isset( $_POST['appending_bonus_data'] ) && $_POST['appending_bonus_data'] == 'yes' ){
			$per_page = 100;
			$paged = isset( $_POST['page_id'] ) ? max( 0, intval( $_POST['page_id'] -1 ) * $per_page ) : 0;

			$error = 0;
			$rowDataCount= 0;
			$countError = 0;
			$countSuccess = 0;
			$insertingCount = 1;
			$rowDataCount = 0;

			$getTempDatas = $wpdb->get_results("SELECT * FROM $tableTemp WHERE 1 ORDER BY `id` ASC LIMIT ".$per_page." OFFSET ".$paged."");
			$referenceArray = array();
			if( $getTempDatas ){
				foreach( $getTempDatas as $getTempData ){
					if( $getTempData->append_status != 1 ){
						$pool_reference = $getTempData->pool_ref;
						$username = ( $getTempData->username != "" ) ? $getTempData->username : '';
						$reference = ( $getTempData->reference != "" ) ? $getTempData->reference : '';
						$eth_address = ( $getTempData->eth_address != "" ) ? $getTempData->eth_address : '';
						$csr_amount_initial = ( $getTempData->csr_amount_initial != "" ) ? str_replace( ',', '', $getTempData->csr_amount_initial) : 0;
						$first_name = ( $getTempData->first_name != "" ) ? $getTempData->first_name : '';
						$last_name = ( $getTempData->last_name != "" ) ? $getTempData->last_name : '';
						$created = ( $getTempData->created != "" ) ? $getTempData->created : '';
						$email = ( $getTempData->email != "" ) ? $getTempData->email : '';
						$week_number = ( $getTempData->week_number != "" ) ? $getTempData->week_number : '';
						$year_number = ( $getTempData->year_number != "" ) ? $getTempData->year_number : '';
						$csr_segmentation = ( $getTempData->csr_segmentation != "" ) ? $getTempData->csr_segmentation : '';
						$import_by = ( $getTempData->import_by != "" ) ? $getTempData->import_by : '';
						$import_date = ( $getTempData->import_date != "" ) ? $getTempData->import_date : '';


						$distribution_status = ( $getTempData->distribution_status != "" ) ? $getTempData->distribution_status : '';
						$member_status = ( $getTempData->member_status != "" ) ? $getTempData->member_status : '';


						if( $csr_amount_initial <= $csr_segmentation ){

							$admNo = $reference.'-000';
							$newAdmNo = ++$admNo;
							$amount_due = $csr_amount_initial;
							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
								$corp_approved_10 = $distribution_status;
							}else{
								$corp_approved_10 = 'Pending';
							}
							$notes_external_10 = '| Pending 10% distribution. |';
							if( $distribution_status == 'Security Hold' ){
								$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
							}
							$notes_external_10 = notes_trim_pipe( $notes_external_10 );

							$text_7 = null;
							if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' ){
								$text_7 = 'Pending';
							}

							$week_number = sprintf("%02d", $week_number);

							$data = array(
								'reference'				=>	$newAdmNo,
								'eth_address'			=>	$eth_address,
								'csr_amount_initial'	=>	$csr_amount_initial,
								'csr_amount_issued'		=>	0,
								'amount_due'			=>	$amount_due,
								'username'				=>	$username,
								'first_name'			=>	$first_name,
								'last_name'				=>	$last_name,
								'redemption_date'		=>	$created,
								'email'					=>	$email,
								'_user_status'			=>	$member_status,
								// 'kyc_status'			=>	$getDistribution->distribution_status,
								'pool_ref'				=>	$pool_reference,
								'corp_approved'			=>	$corp_approved_10,
								'notes_external'		=>	$notes_external_10,
								// 'text_7'				=>	$text_7,
								'text_10'				=>	$year_number.'/'.$week_number,
								// 'text_9'				=>	$getDistribution->source,
								'imported_by'			=>	$import_by,
								'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
							);

							/* $data = [
								'username'					=>	wp_strip_all_tags( $username ),
								'reference'					=>	wp_strip_all_tags( $newAdmNo ),
								'eth_address'				=>	wp_strip_all_tags( $eth_address ),
								'csr_amount_initial'		=>	wp_strip_all_tags( $csr_amount_initial ),
								'first_name'				=>	wp_strip_all_tags( $first_name ),
								'last_name'					=>	wp_strip_all_tags( $last_name ),
								'created'					=>	$created,
								'email'						=>	wp_strip_all_tags( $email ),
								'csr_amount_issued'			=>	0,
								'amount_due'				=>	$amount_due,
								'distribution_status'		=>	$distribution_status,
								'member_status'				=>	$member_status,
								'corp_approved'				=>	$corp_approved_10,
								'notes_external'			=>	$notes_external_10,
								'pool_ref'					=>	$pool_reference,
								'source'					=>	$source,
								'week_number'				=>	$year_number.'/'.$week_number,
								'csr_segmentation'			=>	$csr_segmentation,
								'import_by'					=>	$import_by,
								'import_date'				=>	$import_date,
								'parent_reference'			=>	$reference,
							]; */
							$inserting = $wpdb->insert( $tableTokenHolder, $data );
							if( $inserting ){
								$countSuccess++;
								$user_type = 'sm';
								$log_type = 'weekly_redemptions_append';
								$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
								create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
								$wpdb->update( $tableTempName, array( 'append_status' => 1 ), array( 'id' => $getTempData->id ) );
								// $wpdb->delete( $tableTokenHolder, array( 'reference' => $reference ) );
								$referenceArray[] = $reference;
							}else{
								$error = 1;
								$countError++;
								// $delete = $wpdb->query("TRUNCATE TABLE `".$tableTemp."`");
								$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
								echo wp_json_encode( $out );
								exit;
							}
						}else{

							$csr_amount_pending = $csr_amount_initial;
							$totalNumberWeek = 52;

							$loopCounter = 0;
							for( $i=0; $i < 10; $i++ ){

								$amount_due = $csr_amount_pending / ( 10 - $i );
								$amount_due = ceil( $amount_due );
								//$csr_amount_pending = $csr_amount_pending - $amount_due;

								if( $i == 0 ){
									$admNo = $reference.'-000';
								}else{
									$admNo = $newAdmNo;
								}
								$newAdmNo = ++$admNo;

								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' || $distribution_status == 'Missing CSR address' ){
									$corp_approved_10 = $distribution_status;
								}else{
									$corp_approved_10 = 'Pending';
								}
								$notes_external_10 = '| Pending 10% distribution. |';
								if( $distribution_status == 'Security Hold' ){
									$notes_external_10 = '| Distribution suspended until Security Hold lifted. |' . $notes_external_10;
								}
								$notes_external_10 = notes_trim_pipe( $notes_external_10 );
								if( $week_number > $totalNumberWeek ){
									$week_number = $week_number - $totalNumberWeek;
									$year_number = $year_number + 1;
								}else{
									$year_number = $year_number;
								}

								$new_week_number = $year_number . '/' . sprintf("%02d", $week_number);

								$text_7 = null;
								if( $distribution_status == 'Security Hold' || $distribution_status == 'Hold' ){
									$text_7 = 'Pending';
								}

								$data = array(
									'reference'				=>	$newAdmNo,
									'eth_address'			=>	$eth_address,
									'csr_amount_initial'	=>	$csr_amount_initial,
									'csr_amount_issued'		=>	0,
									'amount_due'			=>	$amount_due,
									'username'				=>	$username,
									'first_name'			=>	$first_name,
									'last_name'				=>	$last_name,
									'redemption_date'		=>	$created,
									'email'					=>	$email,
									'_user_status'			=>	$member_status,
									// 'kyc_status'			=>	$getDistribution->distribution_status,
									'pool_ref'				=>	$pool_reference,
									'corp_approved'			=>	$corp_approved_10,
									'notes_external'		=>	$notes_external_10,
									// 'text_7'				=>	$text_7,
									'text_10'				=>	$new_week_number,
									// 'text_9'				=>	$getDistribution->source,
									'imported_by'			=>	$import_by,
									'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
								);

								/* $data = [
									'username'					=>	wp_strip_all_tags( $username ),
									'reference'					=>	wp_strip_all_tags( $newAdmNo ),
									'eth_address'				=>	wp_strip_all_tags( $eth_address ),
									'csr_amount_initial'		=>	$csr_amount_initial,
									// 'csr_amount_initial'		=>	$csr_amount_pending,
									'first_name'				=>	wp_strip_all_tags( $first_name ),
									'last_name'					=>	wp_strip_all_tags( $last_name ),
									'created'					=>	$created,
									'email'						=>	wp_strip_all_tags( $email ),
									'csr_amount_issued'			=>	0,
									'amount_due'				=>	$amount_due,
									'distribution_status'		=>	$distribution_status,
									'member_status'				=>	$member_status,
									'corp_approved'				=>	$corp_approved_10,
									'notes_external'			=>	$notes_external_10,
									'pool_ref'					=>	$pool_reference,
									'source'					=>	$source,
									'week_number'				=>	$new_week_number,
									'csr_segmentation'			=>	$csr_segmentation,
									'import_by'					=>	$import_by,
									'import_date'				=>	$import_date,
									'parent_reference'			=>	$reference,
								]; */

								$csr_amount_pending = $csr_amount_pending - $amount_due;

								$inserting = $wpdb->insert( $tableTokenHolder, $data );
								if( $inserting ){
									$countSuccess++;
									$loopCounter++;
									$user_type = 'sm';
									$log_type = 'weekly_redemptions_append';
									$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
									create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
								}else{
									$error = 1;
									$countError++;
									$out = array( "error" => 1, 'msg' => sprintf( __('Error : %s row not inserted',CIP_TXTDOMAIN), getOrdinal( $getTempData->id ) ), 'totalCount' => $total_line, 'msg2' => __('An error occurred', CIP_TXTDOMAIN), 'isLastPage' => 'no' );
									echo wp_json_encode( $out );
									exit;
								}
								// $week_number++;
								$week_number = $week_number + 4;

							}
							if( $loopCounter == 10 ){
								$wpdb->update( $tableTempName, array('append_status' => 1), array( 'id' => $getTempData->id ) );
								$referenceArray[] = $reference;
								// $wpdb->delete( $tableTokenHolder, array( 'reference' => $reference ) );
							}
						}

						$rowDataCount = $getTempData->id;
					}
				}
				if( !empty( $referenceArray ) ){
					$wpdb->query('DELETE FROM `'.$tableTokenHolder.'` WHERE `reference` IN ("' . implode('", "', $referenceArray) . '")');
				}
				if( $_POST['total_paged'] == $_POST['page_id'] ){
					$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'yes' );
					// $getAppendedRecords = $wpdb->get_results("SELECT * FROM $tableTempName WHERE 1 AND `append_status` = 1");

					/* $wpdb->delete( $tableTempName, array( 'append_status' => 1 ) );
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`"); */
					/* $countTotalAppened = count( $getAppendedRecords );
					$loopCountTotalAppened = 0;
					if( $getAppendedRecords ){
						foreach( $getAppendedRecords as $getAppendedRecord ){
							// $wpdb->delete( $tableTokenHolder, array( 'reference' => $getAppendedRecord->reference ) );
							$wpdb->query("DELETE FROM `".$tableTokenHolder."` WHERE `reference`='".$getAppendedRecord->reference."' ");
							$loopCountTotalAppened++;
						}
						if( $countTotalAppened == $loopCountTotalAppened ){
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
							$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
						}
					} */
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
					$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
				}else{
					$out = array( "error" => 0,'msg' => sprintf( __('<br>%s: Appended : %s, Failed : %s',CIP_TXTDOMAIN), $rowDataCount, $countSuccess, $countError ), 'isLastPage' => 'no' );
				}
				/* $getProceedCount = $wpdb->get_var("SELECT COUNT(id) FROM $thdTable WHERE 1");
				$importNoticeMsg = sprintf( __('%s row proceed, %s records inserted<br/>', CIP_TXTDOMAIN), $rowDataCount, $getProceedCount );
				// $msg2 = sprintf( __('%s row splitting process complete',CIP_TXTDOMAIN), getOrdinal( $splitting_id ) );
				$out = array( "error" => 0, 'msg' => $importNoticeMsg, 'totalCount' => $rowDataCount ); */
			}
		}
		/* $getDistributionDataCount = $wpdb->get_row("SELECT COUNT(*) as `total_count` FROM $tableName WHERE 1");
		$runCount = 0;
		$successCount = 0;
		$failedCount = 0;
		$total_count = $getDistributionDataCount->total_count;
		$getParentDistributionDatas = $wpdb->get_results("SELECT * FROM $tableTempName WHERE 1");
		if( $getParentDistributionDatas ){
			foreach( $getParentDistributionDatas as $getParentDistributionData ){
				$getDistributionData = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 AND `parent_reference`='". $getParentDistributionData->reference ."'");
				$loopCountTotal = count( $getDistributionData );
				$loopCount = 0;
				if( $getDistributionData ){

					foreach( $getDistributionData as $getDistribution ){

						$runCount++;
						$created_formatted = "";
						if( $getDistribution->created ){
							$formattedCDate = DateTime::createFromFormat('d/m/Y', $getDistribution->created);
							if( $formattedCDate ){
								$created_formatted = $formattedCDate->format('d/m/Y');
							}
						}

						$text_7 = null;
						if( $getDistribution->corp_approved == 'Security Hold' || $getDistribution->corp_approved == 'Hold' ){
							$text_7 = 'Pending';
						}

						$data = array(
							'reference'				=>	$getDistribution->reference,
							'eth_address'			=>	$getDistribution->eth_address,
							'csr_amount_initial'	=>	$getDistribution->csr_amount_initial,
							'csr_amount_issued'		=>	$getDistribution->csr_amount_issued,
							'amount_due'			=>	$getDistribution->amount_due,
							'username'				=>	$getDistribution->username,
							'first_name'			=>	$getDistribution->first_name,
							'last_name'				=>	$getDistribution->last_name,
							'redemption_date'		=>	$created_formatted,
							'email'					=>	$getDistribution->email,
							'_user_status'			=>	$getDistribution->member_status,
							// 'kyc_status'			=>	$getDistribution->distribution_status,
							'pool_ref'				=>	$getDistribution->pool_ref,
							'corp_approved'			=>	$getDistribution->corp_approved,
							'notes_external'		=>	$getDistribution->notes_external,
							// 'text_7'				=>	$text_7,
							'text_10'				=>	$getDistribution->week_number,
							// 'text_9'				=>	$getDistribution->source,
							'imported_by'			=>	$getDistribution->import_by,
							'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
						);
						$inserting = $wpdb->insert( $tableTokenHolder, $data );
						if( $inserting ){
							$successCount++;
							$loopCount++;
							$user_type = 'sm';
							$log_type = 'weekly_redemptions_append';
							$logs = sprintf( __('Appended record to holder %s at %s', CIP_TXTDOMAIN), json_encode( $data ),date_i18n('d/m/Y H:i:s') );
							create_weekly_distribution_cip_logs( $user_type, $log_type, $logs );
							$wpdb->delete( $tableName, array( 'id' => $getDistribution->id ) );

						}else{
							$failedCount++;
							break;
						}
					}
				}
				if( $loopCountTotal == $loopCount ){
					$wpdb->delete( $tableTempName, array( 'reference' => $getParentDistributionData->reference ) );
					$wpdb->delete( $tableTokenHolder, array( 'reference' => $getParentDistributionData->reference ) );
				}
			}
			if( $total_count == $successCount ){
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
				$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
				$out = array( "error" => 0,'msg' => sprintf( __('%s<br/>Total : %s<br/>Appended : %s<br/>Failed : %s',CIP_TXTDOMAIN),$log_msg, $total_count, $successCount, $failedCount  ) );
			}else{
				$log_msg = 'failed :: at '. $runCount .' row to append';
				$out = array( "error" => 1,'msg' => sprintf( __('%s<br/>Total : %s<br/>Appended : %s<br/>Failed : %s',CIP_TXTDOMAIN),$log_msg, $total_count, $successCount, $failedCount  ) );
			}
		} */
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_cancel_append_bonus_process', 'cip_cancel_append_bonus_process_callback' );
function cip_cancel_append_bonus_process_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XYCancelAppendBonusDataYX_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder_distribution';
		$tableTempName = $wpdb->prefix.'token_holder_distribution_temp';
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableName."`");
		$delete = $wpdb->query("TRUNCATE TABLE `".$tableTempName."`");
		if( $delete ){
			$out = array( "error" => 0,'msg' => __('Cancelled',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function get_member_status_from_amplivo( $username = "" ){
	/* $amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
	$amplivo_api_test_source_url = ( !empty( get_option('amplivo_api_test_source_url') ) ) ? get_option('amplivo_api_test_source_url') : 'https://cloudhorizon.sandbox.jox.hu/api/';
	$amplivo_api_live_source_url = ( !empty( get_option('amplivo_api_live_source_url') ) ) ? get_option('amplivo_api_live_source_url') : 'https://amplivo.com/api/';
	$sourceUrl = ( $amplivo_api_mode == 'live' ) ? $amplivo_api_live_source_url : $amplivo_api_test_source_url; */
	$sourceUrl = 'https://amplivo.com/api/';
	$Status = "";
	if( !empty( $sourceUrl ) && !empty( $username ) ){
		$request_url = add_query_arg( 'username', $username, $sourceUrl.'userstatus/get' );
		$response = wp_remote_get( $request_url );
		if( !is_wp_error( $response ) ) {
			$bodyResponse = json_decode( wp_remote_retrieve_body( $response ), true );
			if( isset( $bodyResponse['Status'] ) && !empty( $bodyResponse['Status'] ) ){
				$Status = $bodyResponse['Status'];
			}
		}
	}
	return $Status;
}
// Function to add a custom meta box with a checkbox field to the Page editor.
function csr_add_custom_meta_box() {
    add_meta_box('static_checkbox', 'Page Checkbox', 'csr_render_checkbox_field', 'page');
}
// Callback to render the checkbox field.
function csr_render_checkbox_field($post) {
    // Get the current value of the checkbox.
    $checked = get_post_meta($post->ID, '_static_checkbox', true);
	wp_nonce_field(basename(__FILE__), "meta-box-static-checkbox-nonce");
    ?>
    <label for="static_checkbox_input">
        <input type="checkbox" id="static_checkbox_input" name="static_checkbox" <?php checked($checked, 'on'); ?> /><?php _e('is this static page', 'textdomain'); ?>
    </label>
    <?php
}
// Save the checkbox value when the page is updated.
function csr_save_checkbox_value($post_id) {

	if (!isset($_POST["meta-box-static-checkbox-nonce"]) || !wp_verify_nonce($_POST["meta-box-static-checkbox-nonce"], basename(__FILE__)))
        return $post_id;

	if(defined("DOING_AUTOSAVE") && DOING_AUTOSAVE)
        return $post_id;

    if (isset($_POST['static_checkbox'])) {
        update_post_meta($post_id, '_static_checkbox', 'on');
    } else {
        delete_post_meta($post_id, '_static_checkbox');
    }
}
// Add action hooks to add the meta box and save the checkbox value.
add_action('add_meta_boxes', 'csr_add_custom_meta_box');
add_action('save_post', 'csr_save_checkbox_value');
add_action('template_redirect', 'cip_check_inactive_login_authentication');
function cip_check_inactive_login_authentication(){
	if (is_page()) {
		// Get the current page ID.
        $page_id = get_queried_object_id();

		$login_page_url=get_option( 'login_page_url' );
        // Get the post meta value for a custom field, change 'your_meta_key' to your actual meta key.
        $meta_value = get_post_meta($page_id, '_static_checkbox', true);
		if ($meta_value != 'on') {
			if (isset($_COOKIE['user_logout']) && $_COOKIE['user_logout'] === '1') {
				if(!is_user_logged_in()){
					if( !is_front_page() && $login_page_url != $page_id ){
						wp_redirect(wp_login_url());
						exit();
					}
				}
			} else {
				if(!is_user_logged_in()){
					if( !is_front_page() && $login_page_url != $page_id ){
						wp_redirect( site_url() );
						exit();
					}
				}
			}

        }
	}
}
function set_logout_cookie() {
    setcookie('user_logout', '1', time() + 3600, COOKIEPATH, COOKIE_DOMAIN);
}
add_action('wp_logout', 'set_logout_cookie');
add_action('wp_ajax_withdrawal_disable_after_login_timer','cip_withdrawal_disable_after_login_timer_callback');
function cip_withdrawal_disable_after_login_timer_callback(){

	$expired = new DateTime( date('Y-m-d H:i:s', $_SESSION['logged_time'] ) );
	$now = new DateTime();
	$value = $now->format('%r');
	$countDown = $now->diff($expired, true);
	$e['countDown'] = $countDown;
	$e['value'] = $now->diff($expired)->format("%r%a");
	if( $now->diff($expired)->format("%r%a") == '-0' ){
		// unset( $_SESSION['logged_time'] );
	}
	echo json_encode($e);
	exit;
}
add_action( 'wp_ajax_withdrawal_suspension_minutes_setting_act', 'cip_withdrawal_suspension_minutes_setting_act_callback' );
function cip_withdrawal_suspension_minutes_setting_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_ZyxwithdrawalSuspensionConfigxyZ_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$current_user = wp_get_current_user();
		$withdrawal_suspension_minutes = ( is_numeric(	$_POST['withdrawal_suspension_minutes']) && $_POST['withdrawal_suspension_minutes'] > 0 ) ? $_POST['withdrawal_suspension_minutes'] : 5;
		$oldValue = get_withdrawal_suspension_option( 'min' );
		$logs = sprintf( __('Withdrawal suspension minutes update from %s to %s. by %s at %s.', CIP_TXTDOMAIN), $oldValue, $withdrawal_suspension_minutes, $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'setting', '','sm', $logs, true );
		update_option( 'withdrawal_suspension_minutes', $withdrawal_suspension_minutes );
		$out = array( "error" => 0,'msg' => __('Saved',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
function get_withdrawal_suspension_option( $type = 'sec' ){
	$withdrawal_suspension_minutes = ( is_numeric(	get_option( 'withdrawal_suspension_minutes' ) ) && get_option( 'withdrawal_suspension_minutes' ) > 0 ) ? get_option( 'withdrawal_suspension_minutes' ) : 5;
	if( $type == 'min' ){
		return $withdrawal_suspension_minutes;
	}else{
		return $withdrawal_suspension_minutes * 60;
	}
}
/**
 * create withdrawal block address
 */
add_action('wp_ajax_create_withdrawal_block_address_act', 'create_withdrawal_block_address_act_callback');
function create_withdrawal_block_address_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPWithdrawalBlockAddressCIPY_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableWithdrawalBlockAddress = $wpdb->prefix.'withdrawal_block_address';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$getBlockAddress = $wpdb->get_row("SELECT * FROM $tableWithdrawalBlockAddress WHERE `withdrawal_block_address` = '". $_POST['withdrawal_block_address'] ."'");
		if( !$getBlockAddress ){
			$insert = $wpdb->insert( $tableWithdrawalBlockAddress, ['address_name' => $_POST['address_name'], 'withdrawal_block_address' => $_POST['withdrawal_block_address'], 'internal_note' => $_POST['internal_note'], '_date' => date_i18n('Y-m-d H:i:s'), 'status' => 1] );
			if( $insert ){
				$logs = sprintf( __('Withdrawal block address added by %s at %s. Name: %s, Address: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $_POST['address_name'], $_POST['withdrawal_block_address'] );
				create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
				$out = array( "error" => 0,'msg' => __('Address added',CIP_TXTDOMAIN) );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Address already exists.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * delete withdrawal block address
 */
add_action( 'wp_ajax_delete_withdrawal_block_address_action', 'cip_delete_withdrawal_block_address_action_callback' );
function cip_delete_withdrawal_block_address_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableWithdrawalBlockAddress = $wpdb->prefix.'withdrawal_block_address';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_WithdrawalBlockAdress_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_WithdrawalBlockAdress_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableWithdrawalBlockAddress WHERE 1 AND id = ".$id."");
			if( $getData ){
				$deleting = $wpdb->delete( $tableWithdrawalBlockAddress, ['id' => $id] );
				if( $deleting ){
					$logs = sprintf( __('Withdrawal block address removed by %s at %s. Name: %s, Address: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $getData->address_name, $getData->withdrawal_block_address );
					create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
					$out = array( "error" => 0,'msg' => __('Address deleted',CIP_TXTDOMAIN));
				}else{
					$out = array( "error" => 1,'msg' => __('Address failed to delete',CIP_TXTDOMAIN));
				}

			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Create new corporate user
 */
add_action( 'wp_ajax_create_corporate_user_act', 'cip_create_corporate_user_act_callback' );
function cip_create_corporate_user_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPcreate_corporate_userCIPY_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$getAlreadyHaveUserEmail = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE `email`='".$_POST['corporate_email']."'");
		$getAlreadyHaveUserAddress = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE `eth_address`='".$_POST['csr_wallet_address']."' ");
		if( $getAlreadyHaveUserEmail ){
			$out = array( "error" => 1,'msg' => __('Email already exists.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		if( $getAlreadyHaveUserAddress ){
			$out = array( "error" => 1,'msg' => __('CSR Wallet Address already exists.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
		$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
		if( $decryptedUserId == $user_id ){
			$user_otp = get_user_meta( $user_id, 'user_otp_corporate_user', true );
			$user_otp_expiration = get_user_meta( $user_id, 'user_otp_corporate_user_expiration', true );
			$emailOTPValid = false;
			$gaOTPValid = false;
			if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
				$emailOTPValid = true;
			}
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			if( !empty( $_POST['user_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}
			if( $emailOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			if( $gaOTPValid === false ){
				$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$username = "";
			$getUser = corsair_get_users_from_sourceapi_data( $_POST['corporate_email'] );
			if( $getUser['result'] ){
				$username = $getUser['Username'];
			}

			$data = array(
				'first_name'	=>	$_POST['corporate_user_first_name'],
				'last_name'		=>	$_POST['corporate_user_last_name'],
				'email'			=>	$_POST['corporate_email'],
				'username'		=>	$username,
				'eth_address'	=>	$_POST['csr_wallet_address'],
			);
			$insert = $wpdb->insert( $tableCorporateUsers, $data );
			if( $insert ){
				$logs = sprintf( __('Corporate user created by %s at %s. Corporate user details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode( $data ) );
				create_cip_logs_entery( $current_user->ID, 'corporate_user', '','sm', $logs, true );
				$out = array( "error" => 0,'msg' => __('Corporate user created.',CIP_TXTDOMAIN) );
			}else{
				$out = array( "error" => 1,'msg' => __('Failed to create corporate user.',CIP_TXTDOMAIN) );
			}
		}else{
			$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Get corporate user form for edit
 */
add_action( 'wp_ajax_get_corporate_user_action', 'cip_get_corporate_user_action_callback' );
function cip_get_corporate_user_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$corporate_id = preg_replace(sprintf('/%s/', md5('CIP_CorporateUser_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $corporate_id . md5('CIP_CorporateUser_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE 1 AND id = ".$corporate_id."");
			if( $getData ){
				$clientResendKey = 'resend_attempt_corporate_user' . $client_ip_address;
				if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
					if ((get_transient($clientResendKey) !== false)) {
						$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
				$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$ga2fa_enabled = ( !empty( $google_auth_key ) ) ? 1 : 0;

				if( $corsair_2fa_ga != 'yes' || $ga2fa_enabled != 1 ){
					$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$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_corporate_user', $user_otp );
				update_user_meta( $user_id, 'user_otp_corporate_user_expiration', $user_otp_expiration );
				$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(__("%s - Email OTP Verification for Corporate User", 'corsair-login'), $blogname);
				$message = __('<h2>Confirm Update Corporate User</h2>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
				$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
				$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
				$htmlContent = mailTemplateHtmlRender( $message );
				$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
				if( $sent_mail ){
					$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
					set_transient($clientResendKey, '1', 60);
					ob_start();
					?>
					<span class="modalpopup_close_btn close" data-dismiss="modal">×</span>
					<form class="edit_corporate_user_frm" id="edit_corporate_user_frm" name="edit_corporate_user_frm">
						<div class="form-group">
							<h5><?php _e('Edit Corporate User', CIP_TXTDOMAIN); ?></h5>
						</div>
						<div class="row">
							<div class="col">
								<div class="form-group">
									<input type="text" class="form-control" id="corporate_user_first_name" name="corporate_user_first_name" placeholder="<?php _e('First Name *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->first_name ?>" />
								</div>
							</div>
							<div class="col">
								<div class="form-group">
									<input type="text" class="form-control" id="corporate_user_last_name" name="corporate_user_last_name" placeholder="<?php _e('Last Name *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->last_name ?>" />
								</div>
							</div>
						</div>
						<div class="form-group">
							<input type="email" class="form-control" id="corporate_email" name="corporate_email" placeholder="<?php _e('Email *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->email ?>" />
						</div>
						<div class="form-group">
							<input type="text" class="form-control" id="csr_wallet_address" name="csr_wallet_address" placeholder="<?php _e('CSR Wallet Address *', CIP_TXTDOMAIN); ?>" value="<?php echo $getData->eth_address ?>" />
						</div>
						<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
						<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 mb-1" 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>
						<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_corporate_user_edit" 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_corporate_user_edit').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_corporate_user_edit').text("Resend in "+(sec)+' s')
										}else{
											$('#resend_corporate_user_edit').attr('data-stat','').removeClass('disabled').text('Resend OTP')
											clearInterval(countdown)
										}
									}, 1000);
								}
							});
						</script>
						<hr class="mt-4 mb-3">
						<div class="otp_section pb-3">
							<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
							<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
							<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
						</div>
						<button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
						<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
						<input type="hidden" name="action" value="edit_corporate_user_act" />
						<input type="hidden" name="cu_id" value="<?php echo $_POST['thisId']; ?>" />
						<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
					</form>
					<?php
				}
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Edit corporate user details
 */
add_action( 'wp_ajax_edit_corporate_user_act', 'cip_edit_corporate_user_act_callback' );
function cip_edit_corporate_user_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['cu_id'] );
		$corporate_id = preg_replace(sprintf('/%s/', md5('CIP_CorporateUser_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $corporate_id . md5('CIP_CorporateUser_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE 1 AND id = ".$corporate_id."");
			if( $getData ){
				$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
				if( $decryptedUserId == $user_id ){
					$getAlreadyHaveUserEmail = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE `email`='".$_POST['corporate_email']."' AND `id` != $getData->id");
					$getAlreadyHaveUserAddress = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE `eth_address`='".$_POST['csr_wallet_address']."' AND `id` != $getData->id");
					if( $getAlreadyHaveUserEmail ){
						$out = array( "error" => 1,'msg' => __('Email already exists.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $getAlreadyHaveUserAddress ){
						$out = array( "error" => 1,'msg' => __('CSR Wallet Address already exists.',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$user_otp = get_user_meta( $user_id, 'user_otp_corporate_user', true );
					$user_otp_expiration = get_user_meta( $user_id, 'user_otp_corporate_user_expiration', true );
					$emailOTPValid = false;
					$gaOTPValid = false;
					if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
						$emailOTPValid = true;
					}
					$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
					if( !empty( $_POST['user_ga_otp'] ) ){
						$google2fa = new \PragmaRX\Google2FA\Google2FA();
						if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
							$gaOTPValid = true;
						}
					}
					if( $emailOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $gaOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$data = array(
						'first_name'	=>	$_POST['corporate_user_first_name'],
						'last_name'		=>	$_POST['corporate_user_last_name'],
						'email'			=>	$_POST['corporate_email'],
						// 'username'		=>	$username,
						'eth_address'	=>	$_POST['csr_wallet_address'],
						'update_date'	=>	date_i18n( 'Y-m-d H:i:s' ),
					);
					$where = array( 'id' => $getData->id );
					$update = $wpdb->update( $tableCorporateUsers, $data, $where );
					$updatedData = array();

					$columnArr = array('first_name', 'last_name', 'email', 'eth_address');
					foreach( $columnArr as $columnKey ){
						if( $data[ $columnKey ] != $getData->$columnKey ){
							$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getData->$columnKey, $data[ $columnKey ] );
						}
					}
					if( empty( $updatedData ) ){
						$updatedData[] = json_encode( $data );
					}
					if( $update ){
						$logs = sprintf( __('Corporate user updated by %s at %s. Corporate user details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), implode( ', ', $updatedData ) );
						create_cip_logs_entery( $current_user->ID, 'corporate_user', '','sm', $logs, true );
						$out = array( "error" => 0,'msg' => __('Corporate User Updated.',CIP_TXTDOMAIN) );
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to update.',CIP_TXTDOMAIN) );
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Get corporate user creation form for adding new corporate user
 */
add_action( 'wp_ajax_get_create_corporate_user_form_action', 'cip_get_create_corporate_user_form_action_callback' );
function cip_get_create_corporate_user_form_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( wp_verify_nonce( $_POST['_micro'], $user_id . md5('CIP_CreateModalCorporateUser_CIP') ) ){
			$clientResendKey = 'resend_attempt_corporate_user' . $client_ip_address;
			if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
				if ((get_transient($clientResendKey) !== false)) {
					$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
			}
			$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
			$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
			$ga2fa_enabled = ( !empty( $google_auth_key ) ) ? 1 : 0;

			if( $corsair_2fa_ga != 'yes' || $ga2fa_enabled != 1 ){
				$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$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_corporate_user', $user_otp );
			update_user_meta( $user_id, 'user_otp_corporate_user_expiration', $user_otp_expiration );
			$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(__("%s - Email OTP Verification for Corporate User", 'corsair-login'), $blogname);
			$message = __('<h2>Confirm Add Corporate User</h2>', CIP_TXTDOMAIN );
			$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
			$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
			$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
			$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
			$htmlContent = mailTemplateHtmlRender( $message );
			$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
			if( $sent_mail ){
				$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
				set_transient($clientResendKey, '1', 60);
				ob_start();
				?>
				<span class="modalpopup_close_btn close" data-dismiss="modal">×</span>
				<form class="create_corporate_user_frm" id="create_corporate_user_frm" name="create_corporate_user_frm">
					<div class="form-group">
						<h5><?php _e('Add Create Corporate User', CIP_TXTDOMAIN); ?></h5>
					</div>
					<div class="row">
						<div class="col">
							<div class="form-group">
								<input type="text" class="form-control" id="corporate_user_first_name" name="corporate_user_first_name" placeholder="<?php _e('First Name *', CIP_TXTDOMAIN); ?>" />
							</div>
						</div>
						<div class="col">
							<div class="form-group">
								<input type="text" class="form-control" id="corporate_user_last_name" name="corporate_user_last_name" placeholder="<?php _e('Last Name *', CIP_TXTDOMAIN); ?>" />
							</div>
						</div>
					</div>
					<div class="form-group">
						<input type="email" class="form-control" id="corporate_email" name="corporate_email" placeholder="<?php _e('Email *', CIP_TXTDOMAIN); ?>" />
					</div>
					<div class="form-group">
						<input type="text" class="form-control" id="csr_wallet_address" name="csr_wallet_address" placeholder="<?php _e('CSR Wallet Address *', CIP_TXTDOMAIN); ?>" />
					</div>
					<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
					<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 mb-1" 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>
					<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_corporate_user_add" 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_corporate_user_add').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_corporate_user_add').text("Resend in "+(sec)+' s')
									}else{
										$('#resend_corporate_user_add').attr('data-stat','').removeClass('disabled').text('Resend OTP')
										clearInterval(countdown)
									}
								}, 1000);
							}
						});
					</script>
					<hr class="mt-4 mb-3">
					<div class="otp_section pb-3">
						<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
						<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
						<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
					</div>
					<button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
					<input type="hidden" name="action" value="create_corporate_user_act" />
					<input type="hidden" name="pageid" value="<?php echo get_the_id(); ?>" />
					<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YCIPcreate_corporate_userCIPY_'); ?>" />
				</form>
				<?php
			}
			$html = ob_get_clean();
			$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 *
 */
add_action( 'wp_ajax_checkingCorporateUserRequestWithdrawals', 'checkingCorporateUserRequestWithdrawals_callback' );
function checkingCorporateUserRequestWithdrawals_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCorporateUserRequestWithdrawalsyX_' ) && current_user_can( 'supportagent' ) ){
		$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
		$tokenType = isset( $_POST['tokenType'] ) ? $_POST['tokenType'] : 'csr';
		/* $sessionSelectionDataEncrypt = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
		$sessionSelectionData = array();
		if( !empty( $sessionSelectionDataEncrypt ) ){
			foreach( $sessionSelectionDataEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);
				$sessionSelectionData[] = $decryptedUserId;
			}
		} */
		$corporateUsersIdsEncrypt = ( isset( $_POST['corporateUsersIds'] ) && !empty( $_POST['corporateUsersIds'] ) ) ? $_POST['corporateUsersIds'] : array();
		$corporateUsersIdsData = array();
		if( !empty( $corporateUsersIdsEncrypt ) ){
			foreach( $corporateUsersIdsEncrypt as $encryptId ){
				$decryptedIdRaw = base64_decode( $encryptId );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_CURWSELECTION_PIC') ), '', $decryptedIdRaw);
				$corporateUsersIdsData[] = $decryptedUserId;
			}
		}
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		// $corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );
		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

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

		if( !in_array( $tokenType, array( 'csr', 'csr25' ) ) ){
			$out = array( "error" => 1,'msg' => __('Invalid token type.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}

		/* $sessionDataQry = "";
		if( $isSelectAll == 1 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` NOT IN ('. implode(',', $sessionSelectionData) .')';
		}else if( $isSelectAll == 0 && !empty( $sessionSelectionData ) ){
			$sessionDataQry = ' AND `id` IN ('. implode(',', $sessionSelectionData) .')';
		} */
		$sessionDataQry = "";
		$sessionDataQry = ' AND `id` IN ('. implode(',', $corporateUsersIdsData) .')';
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';

		$filter_qry = "";
		$filters = json_decode( stripslashes( $_REQUEST['thisParams'] ), true );
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCorporateUsers WHERE 1 $sessionDataQry");
		if( !empty( $filters ) ){
			foreach( $filters as $filterKey => $filterData ){
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCorporateUsers WHERE 1 $filter_qry $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableCorporateUsers WHERE 1 $filter_qry $sessionDataQry ORDER BY `id` DESC");
		$tableList = "";
		$totalWithdrawalRequestCorporateUser = 0;
		$totalCsrAmount = 0;
		ob_start();
		if( $getCurrentMembers ){
			?><table class="table table-bordered"><?php
			foreach( $getCurrentMembers as $getCurrentMember ){
				$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_CURWSELECTION_PIC') );
				$balance_csr_central = get_user_csr_balance( $getCurrentMember->email, 'available', $tokenType );
				$totalCsrAmount += $balance_csr_central;
				if( $balance_csr_central > 0 ){
					?>
					<tr>
						<td><?php echo trim( $getCurrentMember->first_name . ' ' . $getCurrentMember->last_name ); ?></td>
						<td class="eth_address"><a><?php echo trim( $getCurrentMember->eth_address ); ?></a></td>
						<td><?php echo number_format( $balance_csr_central, 2 ); ?></td>
					</tr>
					<input type="hidden" name="corporateUsersIds[]" value="<?php echo $rowEncryptId; ?>" />
					<?php
					$totalWithdrawalRequestCorporateUser++;
				}
			}
			?></table><?php
		}
		$tableList .= ob_get_clean();
		$html = "";
		$clientResendKey = 'resend_attempt_corporate_user_withdrawal_request' . $client_ip_address;
		if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
			if ((get_transient($clientResendKey) !== false)) {
				$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
		}
		$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
		$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
		$ga2fa_enabled = ( !empty( $google_auth_key ) ) ? 1 : 0;

		if( $corsair_2fa_ga != 'yes' || $ga2fa_enabled != 1 ){
			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$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_corporate_user', $user_otp );
		update_user_meta( $user_id, 'user_otp_corporate_user_expiration', $user_otp_expiration );
		$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(__("%s - Email OTP Verification for Withdrawal Request for Corporate User", 'corsair-login'), $blogname);
		$message = __('<h2>Confirm Withdrawal Request for Corporate User</h2>', CIP_TXTDOMAIN );
		$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
		$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
		$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
		$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
		$htmlContent = mailTemplateHtmlRender( $message );
		$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
		if( $sent_mail ){
			$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
			set_transient($clientResendKey, '1', 60);
			ob_start();
			?>
			<h5><?php echo __('Corporate Withdrawals', CIP_TXTDOMAIN); ?></h5>
			<form name="corporateuser_request_withdrawal_frm" id="corporateuser_request_withdrawal_frm">
				<p><?php echo sprintf( __('You are creating %s withdrawal request for Corporate Members', CIP_TXTDOMAIN ), $totalWithdrawalRequestCorporateUser ); ?></p>

				<?php echo $tableList; ?>

				<p><?php echo sprintf( __('%s %s to %s members.', CIP_TXTDOMAIN ), number_format( $totalCsrAmount, 2 ), strtoupper( $tokenType ), $totalWithdrawalRequestCorporateUser ); ?></p>

				<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
				<hr class="mt-4 mb-3">
				<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 mb-1" 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>
				<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_corporate_user_withdrawal_request" 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_corporate_user_withdrawal_request').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_corporate_user_withdrawal_request').text("Resend in "+(sec)+' s')
								}else{
									$('#resend_corporate_user_withdrawal_request').attr('data-stat','').removeClass('disabled').text('Resend OTP')
									clearInterval(countdown)
								}
							}, 1000);
						}
					});
				</script>
				<hr class="mt-4 mb-3">
				<div class="otp_section pb-3">
					<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
					<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
					<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
				</div>
				<input type="hidden" name="action" value="corporateUserWithdrawalRequestAction" />
				<input type="hidden" name="tokenType" value="<?php echo $tokenType; ?>" />
				<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_XyCorporateUserRequestWithdrawalActyX_'); ?>" />
				<input type="submit" class="btn btn-primary" name="submit" value="<?php _e('Submit', CIP_TXTDOMAIN); ?>" />
			</form>
			<?php
		}
		$html .= ob_get_clean();
		$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 *
 */
add_action( 'wp_ajax_corporateUserWithdrawalRequestAction', 'cip_corporateUserWithdrawalRequestAction_callback' );
function cip_corporateUserWithdrawalRequestAction_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( wp_verify_nonce( $_POST['_micro'], '_XyCorporateUserRequestWithdrawalActyX_' ) ){

			$tokenType = ( isset( $_POST['tokenType'] ) && !empty( $_POST['tokenType'] ) ) ? $_POST['tokenType'] : 'csr';
			if( !in_array( $tokenType, array( 'csr', 'csr25' ) ) ){
				$out = array( "error" => 1,'msg' => __('Invalid token type.',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}

			$corporateUsersIdsEncrypt = ( isset( $_POST['corporateUsersIds'] ) && !empty( $_POST['corporateUsersIds'] ) ) ? $_POST['corporateUsersIds'] : array();
			$corporateUsersIdsData = array();
			if( !empty( $corporateUsersIdsEncrypt ) ){
				foreach( $corporateUsersIdsEncrypt as $encryptId ){
					$decryptedIdRaw = base64_decode( $encryptId );
					$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_CURWSELECTION_PIC') ), '', $decryptedIdRaw);
					$corporateUsersIdsData[] = $decryptedUserId;
				}
			}
			$sessionDataQry = "";
			$sessionDataQry = ' AND `id` IN ('. implode(',', $corporateUsersIdsData) .')';
			$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableCorporateUsers WHERE 1 $sessionDataQry ORDER BY `id` DESC");
			$withdrawalProceed = 0;
			if( $getCurrentMembers ){
				$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
				if( $decryptedUserId == $user_id ){
					$user_otp = get_user_meta( $user_id, 'user_otp_corporate_user', true );
					$user_otp_expiration = get_user_meta( $user_id, 'user_otp_corporate_user_expiration', true );
					$emailOTPValid = false;
					$gaOTPValid = false;
					if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
						$emailOTPValid = true;
					}
					$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
					if( !empty( $_POST['user_ga_otp'] ) ){
						$google2fa = new \PragmaRX\Google2FA\Google2FA();
						if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
							$gaOTPValid = true;
						}
					}
					if( $emailOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $gaOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
					$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
					$tableTokenHolder = $wpdb->prefix.'token_holder';
					$withdrawal_fee = 0;

					foreach( $getCurrentMembers as $getCurrentMember ){
						$username = "";
						$first_name = $getCurrentMember->first_name;
						$last_name = $getCurrentMember->last_name;
						$getUsername = $wpdb->get_row("SELECT `first_name`,`last_name`,`username` FROM $tableTokenHolder WHERE `email`='".$getCurrentMember->email."' ORDER BY `id` DESC");
						if( $getUsername ){
							$username = $getUsername->username;
							// $first_name = $getUsername->first_name;
							// $last_name = $getUsername->last_name;
						}
						$member_user_id = 0;
						$memberUserData = get_user_by('email', $getCurrentMember->email);
						if( $memberUserData ){
							$member_user_id = $memberUserData->ID;
						}
						if( $emailOTPValid === true && $gaOTPValid === true ){
							$balance_csr_central = get_user_csr_balance( $getCurrentMember->email, 'available', $tokenType );
							if( $balance_csr_central > 0 ){

								$minimum_withdrawal_amount = 0;
								$received_amount = $balance_csr_central - $withdrawal_fee;
								$withdrawal_id = uniqidReal();

								if( empty( $withdrawal_id ) ){
									$out = array( "error" => 1,'msg' => __('Error occurred during withdrawal, Please try agian', CIP_TXTDOMAIN) );
									echo wp_json_encode( $out );
									exit;
								}
								$data = array(
									'user_id'				=>	$member_user_id,
									'withdrawal_id'			=>	$withdrawal_id,
									'username'				=>	$username,
									'first_name'			=>	$first_name,
									'last_name'				=>	$last_name,
									'email'					=>	$getCurrentMember->email,
									'eth_address'			=>	$getCurrentMember->eth_address,
									'withdraw_amount'		=>	$received_amount,
									'min_withdraw_amount'	=>	$minimum_withdrawal_amount,
									'withdrawal_fee'		=>	$withdrawal_fee,
									'received_amount'		=>	$received_amount,
									'status'				=>	0,
									'requested_date'		=>	date_i18n('Y-m-d H:i:s'),
									'amount_to_distribute'	=>	$received_amount,
									'withdrawal_process_status' => 'Pending',
									'token'					=>	strtoupper( $tokenType ),
								);
								$star_request_url = add_query_arg( 'email', urlencode( $getCurrentMember->user_email ), 'https://amplivo.com/api/userstatus/get' );
								$star_response = wp_remote_get( $star_request_url );
								if( !is_wp_error( $star_response ) ) {
									$star_response_body = wp_remote_retrieve_body( $star_response );
									$star_data = json_decode( $star_response_body );
									if(isset( $star_data->Star_1 )){
										$user_star = 1;
									}
									if(isset( $star_data->Star_2 )){
										$user_star = 2;
									}
									if(isset( $star_data->Star_3 )){
										$user_star = 3;
									}
									if(isset( $star_data->Star_4 )){
										$user_star = 4;
									}
									if(isset( $star_data->Star_5 )){
										$user_star = 5;
									}
									if(isset( $star_data->Star_6 )){
										$user_star = 6;
									}
									if(isset( $star_data->Star_7 )){
										$user_star = 7;
									}
									if(isset( $user_star)){
										$data['user_star'] = $user_star;
									}
								}
								$insert = $wpdb->insert( $tableWithdraw, $data );
								if( $insert ){
									$lastid = $wpdb->insert_id;

									//notice of withdrawal request
									$tableCipNotice = $wpdb->prefix.'cip_notice';
									$notificationMessageText = sprintf( __('Your withdrawal request for %s %s is now being reviewed and processed.', CIP_TXTDOMAIN), number_format( $received_amount, 2 ), strtoupper( $tokenType ) );
									$noticeData = array(
										"email"		=>	$getCurrentMember->email,
										"username"	=>	'',
										"notice"	=>	$notificationMessageText,
										"status"	=>	1,
										"notice_date"	=>	date_i18n( 'Y-m-d H:i:s' ),
									);
									$wpdb->insert( $tableCipNotice, $noticeData );

									$logs = sprintf( __('Withdrawal request behalf of member (%s) of %s %s to Blockchain address %s, Withdrawal-ID: %s by %s at %s. IP: %s', CIP_TXTDOMAIN), $getCurrentMember->email, number_format( $received_amount, 2 ), strtoupper( $tokenType ), $getCurrentMember->eth_address, $withdrawal_id, $current_user->user_email, date_i18n('d/m/Y H:i A'), cip_get_client_ip() );
									create_cip_logs_entery( $member_user_id, 'withdraw', '','member', $logs, true );
									$reason = __('This withdrawal on behalf of the member', CIP_TXTDOMAIN);

									$transactionData = array(
										'user_id'			=>	$member_user_id,
										'txn_id'			=>	$withdrawal_id,
										'txn_id_ref'		=>	$withdrawal_id,
										'email'				=>	$getCurrentMember->email,
										'username'			=>	$username,
										'eth_address'		=>	$getCurrentMember->eth_address,
										'withdrawal_amount'	=>	$received_amount,
										'received_amount'	=>	$received_amount,
										'withdrawal_fee'	=>	$withdrawal_fee,
										'type'				=>	'withdrawal',
										'description'		=>	$logs,
										'short_description'	=>	sprintf( __('%s withdrawn to blockchain', CIP_TXTDOMAIN), strtoupper( $tokenType ) ),
										'_date'				=>	date_i18n('Y-m-d H:i:s'),
										'status'			=>	0,
										'behalf_member'		=>	1,
										'token'				=>	strtoupper( $tokenType ),
									);
									$transInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );
									$withdrawalProceed++;
								}
							}
						}
					}
					if( $withdrawalProceed > 0 ){
						$msg = sprintf( __('%s withdrawal requested', CIP_TXTDOMAIN ), $withdrawalProceed );
						$out = array( "error" => 0,'msg' => $msg );
					}else{
						$out = array( "error" => 1,'msg' => __('Failed withdrawal request process. please try again.', CIP_TXTDOMAIN) );
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Get corporate user form for delete
 */
add_action( 'wp_ajax_get_corporate_user_delete_action', 'cip_get_corporate_user_delete_action_callback' );
function cip_get_corporate_user_delete_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$corporate_id = preg_replace(sprintf('/%s/', md5('CIP_CorporateUser_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $corporate_id . md5('CIP_CorporateUser_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE 1 AND id = ".$corporate_id."");
			if( $getData ){
				$clientResendKey = 'resend_attempt_corporate_user' . $client_ip_address;
				if( isset( $_POST['resend'] ) && $_POST['resend'] == 1 ){
					if ((get_transient($clientResendKey) !== false)) {
						$out = array( "error" => 1,'msg' => __('You can resend OTP after timer reset', CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
				}
				$corsair_2fa_ga = get_option( 'corsair_2fa_ga' );
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
				$ga2fa_enabled = ( !empty( $google_auth_key ) ) ? 1 : 0;

				if( $corsair_2fa_ga != 'yes' || $ga2fa_enabled != 1 ){
					$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$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_corporate_user', $user_otp );
				update_user_meta( $user_id, 'user_otp_corporate_user_expiration', $user_otp_expiration );
				$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(__("%s - Email OTP Verification for Corporate User", 'corsair-login'), $blogname);
				$message = __('<h2>Confirm Delete Corporate User</h2>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p style="margin-bottom:5px;">Verification code: <br><h3 style="margin:0;"><b>%s</b></h3></p>', CIP_TXTDOMAIN ), $user_otp );
				$message .= __('<p>The verification code will expire after 30 minutes. Do not share your code with anyone.</p>', CIP_TXTDOMAIN );
				$message .= sprintf( __('<p>Don\'t recognize this activity? Please goto <a href="%s">%s</a>, login and change your security settings and contact customer support immediately.</p>', CIP_TXTDOMAIN), $siteUrl, $siteUrlName );
				$message .= __('<p><i>This is an automated message, please do not reply.</i></p>', CIP_TXTDOMAIN );
				$htmlContent = mailTemplateHtmlRender( $message );
				$sent_mail = wp_mail( $current_user->user_email, $subject, $htmlContent );
				if( $sent_mail ){
					$encryptId = base64_encode( $current_user->ID . md5('CL_RESEND_CL'));
					set_transient($clientResendKey, '1', 60);
					ob_start();
					?>
					<span class="modalpopup_close_btn close" data-dismiss="modal">×</span>
					<form class="delete_corporate_user_frm" id="delete_corporate_user_frm" name="delete_corporate_user_frm">
						<div class="form-group">
							<h5><?php _e('Delete Corporate User', CIP_TXTDOMAIN); ?></h5>
						</div>
						<div class="row">
							<div class="col">
								<table class="table table-borderless">
									<tr>
										<td>First Name</td>
										<td><?php echo $getData->first_name ?></td>
									</tr>
									<tr>
										<td>Last Name</td>
										<td><?php echo $getData->last_name ?></td>
									</tr>
									<tr>
										<td>Email</td>
										<td><?php echo $getData->email ?></td>
									</tr>
									<tr>
										<td>CSR Wallet Address</td>
										<td><?php echo $getData->eth_address ?></td>
									</tr>
								</table>
							</div>
						</div>
						<input type="hidden" name="microtoken" value="<?php echo $encryptId; ?>"  />
						<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 mb-1" 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>
						<a class="btn btn-primary bg-gradient disabled" data-stat="countdown" href="javascript:void(0);" id="resend_corporate_user_delete" 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_corporate_user_delete').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_corporate_user_delete').text("Resend in "+(sec)+' s')
										}else{
											$('#resend_corporate_user_delete').attr('data-stat','').removeClass('disabled').text('Resend OTP')
											clearInterval(countdown)
										}
									}, 1000);
								}
							});
						</script>
						<hr class="mt-4 mb-3">
						<div class="otp_section pb-3">
							<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
							<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
							<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
						</div>
						<button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
						<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
						<input type="hidden" name="action" value="delete_corporate_user_act" />
						<input type="hidden" name="cu_id" value="<?php echo $_POST['thisId']; ?>" />
						<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
					</form>
					<?php
				}
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Delete corporate user details
 */
add_action( 'wp_ajax_delete_corporate_user_act', 'cip_delete_corporate_user_act_callback' );
function cip_delete_corporate_user_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCorporateUsers = $wpdb->prefix.'corporate_users';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['cu_id'] );
		$corporate_id = preg_replace(sprintf('/%s/', md5('CIP_CorporateUser_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $corporate_id . md5('CIP_CorporateUser_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCorporateUsers WHERE 1 AND id = ".$corporate_id."");
			if( $getData ){
				$decryptedIdRaw = base64_decode( $_POST['microtoken'] );
				$decryptedUserId = preg_replace(sprintf('/%s/', md5('CL_RESEND_CL') ), '', $decryptedIdRaw);
				if( $decryptedUserId == $user_id ){
					$user_otp = get_user_meta( $user_id, 'user_otp_corporate_user', true );
					$user_otp_expiration = get_user_meta( $user_id, 'user_otp_corporate_user_expiration', true );
					$emailOTPValid = false;
					$gaOTPValid = false;
					if( strtotime($user_otp_expiration) > time() && $user_otp == $_POST['user_otp'] ){
						$emailOTPValid = true;
					}
					$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
					if( !empty( $_POST['user_ga_otp'] ) ){
						$google2fa = new \PragmaRX\Google2FA\Google2FA();
						if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
							$gaOTPValid = true;
						}
					}
					if( $emailOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Expired or Invalid OTP',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}
					if( $gaOTPValid === false ){
						$out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
						echo wp_json_encode( $out );
						exit;
					}

					$deletData = array(
						'first_name'	=>	$getData->first_name,
						'last_name'		=>	$getData->last_name,
						'email'			=>	$getData->email,
						'eth_address'	=>	$getData->eth_address,
					);
					$where = array( 'id' => $getData->id );
					$delete = $wpdb->delete( $tableCorporateUsers, $where );
					if( $delete ){
						$logs = sprintf( __('Corporate user deleted by %s at %s. Corporate user details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode( $deletData ) );
						create_cip_logs_entery( $current_user->ID, 'corporate_user', '','sm', $logs, true );
						$out = array( "error" => 0,'msg' => __('Corporate User Deleted.',CIP_TXTDOMAIN) );
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to delete',CIP_TXTDOMAIN) );
					}
				}else{
					$out = array( "error" => 1,'msg' => __('Authentication failed. Please try again or contact an admin',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sm_price_api_settings_act','cip_sm_price_api_settings_act_cb');
function cip_sm_price_api_settings_act_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_CIPxspricemapisettingxCIP_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$updated_data = array();
		if(isset($_POST['amplivo_api_mode']) && !empty($_POST['amplivo_api_mode'])){
			update_option('amplivo_api_mode',$_POST['amplivo_api_mode']);
			$updated_data['api_mode'] = $_POST['amplivo_api_mode'];
		}
		if(isset($_POST['amplivo_api_live_source_url']) && !empty($_POST['amplivo_api_live_source_url'])){
			update_option('amplivo_api_live_source_url',$_POST['amplivo_api_live_source_url']);
			$updated_data['live_api_url'] = $_POST['amplivo_api_live_source_url'];
		}
		if(isset($_POST['amplivo_api_test_source_url']) && !empty($_POST['amplivo_api_test_source_url'])){
			update_option('amplivo_api_test_source_url',$_POST['amplivo_api_test_source_url']);
			$updated_data['test_api_url'] = $_POST['amplivo_api_test_source_url'];
		}
		if(isset($_POST['amplivo_api_auth_username']) && !empty($_POST['amplivo_api_auth_username'])){
			update_option('amplivo_api_auth_username',$_POST['amplivo_api_auth_username']);
			$updated_data['api_auth_username'] = $_POST['amplivo_api_auth_username'];
		}
		if(isset($_POST['amplivo_api_auth_pwd']) && !empty($_POST['amplivo_api_auth_pwd'])){
			update_option('amplivo_api_auth_pwd',$_POST['amplivo_api_auth_pwd']);
			$updated_data['api_auth_password'] = $_POST['amplivo_api_auth_pwd'];
		}
		$current_user = wp_get_current_user();
		$logs = sprintf( __('API updated by %s at %s. API details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode( $updated_data ) );
		create_cip_logs_entery( $current_user->ID, 'api_update_setting',$logs, true );
		/*update_option( 'csr_wallet_api_mode_test_tkn', $_POST['csr_wallet_api_mode_test_tkn'] );
		update_option( 'csr_wallet_api_mode_test_api', $_POST['csr_wallet_api_mode_test_api'] );
		update_option( 'csr_wallet_api_mode_live_tkn', $_POST['csr_wallet_api_mode_live_tkn'] );
		update_option( 'csr_wallet_api_mode_live_api', $_POST['csr_wallet_api_mode_live_api'] );*/
		$out = array( "error" => 0,'msg' => __('Updated',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Get distribution weeks
 */
add_action( 'wp_ajax_distribution_week_fetch_act', 'cip_distribution_week_fetch_act_callback' );
function cip_distribution_week_fetch_act_callback(){
	global $wpdb;
	$out = array();
	$tableName = $wpdb->prefix.'token_holder';
	$get_distribution_weeks = $wpdb->get_results("SELECT DISTINCT `text_10` FROM $tableName WHERE `text_10` like '".$_REQUEST['search']."%'");
	if( $get_distribution_weeks ){
		foreach( $get_distribution_weeks as $get_distribution_week ){
			$out[] = array(
				'id'	=>	$get_distribution_week->text_10,
				'text'	=>	$get_distribution_week->text_10,
			);
		}
	}
	echo wp_json_encode( array( 'results' => $out ) );
	exit;
}
/**
 * Create CSR pool report
 */
add_action( 'wp_ajax_create_csr_pool_report_act', 'cip_create_csr_pool_report_act_callback' );
function cip_create_csr_pool_report_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_YCIPCSRPoolReportCIPY_' ) && current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( empty( $_POST['distribution_status'] ) && empty( $_POST['pool_reference'] ) && empty( $_POST['distribution_week'] ) && empty( $_POST['amount_due_condition_value'] ) ){
			$out = array( "error" => 1,'msg' => __('Please select at least one option',CIP_TXTDOMAIN) );
			echo wp_json_encode( $out );
			exit;
		}
		$poolReportQry = "";
		if( !empty( $_POST['distribution_status'] ) ){
			$poolReportQry .= " AND `corp_approved`='".$_POST['distribution_status']."'";
		}
		if( !empty( $_POST['pool_reference'] ) ){
			$poolReportQry .= " AND `pool_ref`='".$_POST['pool_reference']."'";
		}
		if( !empty( $_POST['distribution_week'] ) ){
			$poolReportQry .= " AND `text_10`='".$_POST['distribution_week']."'";
		}
		if( !empty( $_POST['amount_due_condition'] ) && !empty( $_POST['amount_due_condition_value'] ) ){
			$amount_due_condition = $_POST['amount_due_condition'];
			if( str_contains($amount_due_condition, '>') || str_contains($amount_due_condition, '>=') || str_contains($amount_due_condition, '<') || str_contains($amount_due_condition, '<=') || str_contains($amount_due_condition, '!=') || str_contains($amount_due_condition, '=') ){
				$poolReportQry .= " AND `amount_due` ".$amount_due_condition." ".$_POST['amount_due_condition_value']."";
			}
		}
		$getTokenHolderData = $wpdb->get_row("SELECT COALESCE(SUM(`csr_amount_initial`),0) as `csr_amount_initial_total`, COALESCE(SUM(`csr_amount_issued`),0) as `csr_amount_issued_total`, COALESCE(SUM(`amount_due`),0) as `amount_due_total` FROM `$tableTokenHolder` WHERE 1 $poolReportQry");
		$data = array(
			'distribution_status'			=>	$_POST['distribution_status'],
			'pool_reference'				=>	$_POST['pool_reference'],
			'distribution_week'				=>	$_POST['distribution_week'],
			'amount_due_condition'			=>	$_POST['amount_due_condition'],
			'amount_due_condition_value'	=>	( $_POST['amount_due_condition_value'] ) ? $_POST['amount_due_condition_value'] : NULL,
			'csr_initial_amount'			=>	$getTokenHolderData->csr_amount_initial_total,
			'csr_distributed'				=>	$getTokenHolderData->csr_amount_issued_total,
			'amount_due'					=>	$getTokenHolderData->amount_due_total,
			'create_date'					=>	date_i18n( 'Y-m-d H:i:s' ),
			'last_update'					=>	date_i18n( 'Y-m-d H:i:s' ),
		);
		$insert = $wpdb->insert( $tableCsrPoolReports, $data );
		if( $insert ){
			// unset( $data['create_date'] );
			unset( $data['last_update'] );
			$logs = sprintf( __('CSR Pool Report Added by %s at %s. Pool Report Details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode( $data ) );
			create_cip_logs_entery( $current_user->ID, 'csr_pool_report', '','sa', $logs, true );
			$out = array( "error" => 0,'msg' => __('CSR Pool Report created.',CIP_TXTDOMAIN) );
		}else{
			$out = array( "error" => 1,'msg' => __('Failed to add CSR Pool Report.',CIP_TXTDOMAIN) );
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * delete csr pool report
 */
add_action( 'wp_ajax_delete_csr_pool_report_action', 'cip_delete_csr_pool_report_action_callback' );
function cip_delete_csr_pool_report_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_CSRPoolReports_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_CSRPoolReports_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrPoolReports WHERE 1 AND id = ".$id."");
			if( $getData ){
				$deleting = $wpdb->delete( $tableCsrPoolReports, ['id' => $id] );
				if( $deleting ){
					unset( $getData->id );
					unset( $getData->create_date );
					unset( $getData->last_update );
					$logs = sprintf( __('CSR Pool Report removed by %s at %s. Details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode( $getData ) );
					create_cip_logs_entery( $user_id, 'csr_pool_report', '','sa', $logs, true );
					$out = array( "error" => 0,'msg' => __('CSR Pool Report deleted',CIP_TXTDOMAIN));
				}else{
					$out = array( "error" => 1,'msg' => __('CSR Pool Report failed to delete',CIP_TXTDOMAIN));
				}

			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Get csr pool report form for edit
 */
add_action( 'wp_ajax_get_csr_pool_report_action', 'cip_get_csr_pool_report_action_callback' );
function cip_get_csr_pool_report_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$report_id = preg_replace(sprintf('/%s/', md5('CIP_CSRPoolReports_CIP') ), '', $decryptedId_raw);
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$getDistributionStatus = $wpdb->get_results( "SELECT `corp_approved` FROM $tableTokenHolder GROUP BY `corp_approved`" );
		if( wp_verify_nonce( $_POST['_micro'], $report_id . md5('CIP_CSRPoolReports_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrPoolReports WHERE 1 AND id = ".$report_id."");
			if( $getData ){
				ob_start();
				?>
				<span class="modalpopup_close_btn close" data-dismiss="modal">×</span>
				<form class="edit_csrpoolreport_frm" id="edit_csrpoolreport_frm" name="edit_csrpoolreport_frm">
					<div class="form-group">
						<h5><?php _e('Edit CSR Pool Report', CIP_TXTDOMAIN); ?></h5>
					</div>
					<div class="row">
						<div class="col-12">
							<div class="form-group">
								<label><?php _e('Distribution Status', CIP_TXTDOMAIN); ?></label>
								<select class="form-control" name="distribution_status">
									<option value="" selected disabled><?php _e('Select Distribution Status', CIP_TXTDOMAIN); ?></option>
									<?php
									if( $getDistributionStatus ){
										foreach( $getDistributionStatus as $distributionStatus){
											?><option value="<?php echo $distributionStatus->corp_approved ?>" <?php selected( $getData->distribution_status, $distributionStatus->corp_approved, true ); ?> ><?php echo $distributionStatus->corp_approved ?></option><?php
										}
									}
									?>
								</select>
							</div>
						</div>
						<div class="col-12">
							<div class="form-group">
								<label><?php _e('Pool Reference', CIP_TXTDOMAIN); ?></label>
								<select class="form-control" name="pool_reference">
									<option value="<?php echo $getData->pool_reference ?>"><?php echo $getData->pool_reference ?></option>
								</select>
							</div>
						</div>
						<div class="col-12">
							<div class="form-group">
								<label><?php _e('Distribution Week', CIP_TXTDOMAIN); ?></label>
								<select class="form-control" name="distribution_week">
									<option value="<?php echo $getData->distribution_week ?>"><?php echo $getData->distribution_week ?></option>
								</select>
							</div>
						</div>
						<div class="col-12">
							<label><?php _e('Amount Due', CIP_TXTDOMAIN); ?></label>
							<div class="input-group mb-3">
								<div class="input-group-prepend">
									<select class="form-control" name="amount_due_condition">
										<option value=""></option>
										<option value="<" <?php selected( $getData->amount_due_condition, '<', true ); ?>><?php echo '<'; ?></option>
										<option value="=" <?php selected( $getData->amount_due_condition, '=', true ); ?>><?php echo '='; ?></option>
										<option value=">" <?php selected( $getData->amount_due_condition, '>', true ); ?>><?php echo '>'; ?></option>
										<option value=">=" <?php selected( $getData->amount_due_condition, '>=', true ); ?>><?php echo '>='; ?></option>
										<option value="<=" <?php selected( $getData->amount_due_condition, '<=', true ); ?>><?php echo '<='; ?></option>
									</select>
								</div>
								<input type="text" class="form-control" name="amount_due_condition_value" value="<?php echo $getData->amount_due_condition_value ?>" />
							</div>
						</div>
					</div>

					<button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
					<button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
					<input type="hidden" name="action" value="edit_csrpoolreport_act" />
					<input type="hidden" name="pr_id" value="<?php echo $_POST['thisId']; ?>" />
					<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />
				</form>
				<?php
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Edit csr pool report details
 */
add_action( 'wp_ajax_edit_csrpoolreport_act', 'cip_edit_csrpoolreport_act_callback' );
function cip_edit_csrpoolreport_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['pr_id'] );
		$report_id = preg_replace(sprintf('/%s/', md5('CIP_CSRPoolReports_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $report_id . md5('CIP_CSRPoolReports_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrPoolReports WHERE 1 AND id = ".$report_id."");
			if( $getData ){
				if( empty( $_POST['distribution_status'] ) && empty( $_POST['pool_reference'] ) && empty( $_POST['distribution_week'] ) && empty( $_POST['amount_due_condition_value'] ) ){
					$out = array( "error" => 1,'msg' => __('Please select at least one option',CIP_TXTDOMAIN) );
					echo wp_json_encode( $out );
					exit;
				}
				$poolReportQry = "";
				if( !empty( $_POST['distribution_status'] ) ){
					$poolReportQry .= " AND `corp_approved`='".$_POST['distribution_status']."'";
				}
				if( !empty( $_POST['pool_reference'] ) ){
					$poolReportQry .= " AND `pool_ref`='".$_POST['pool_reference']."'";
				}
				if( !empty( $_POST['distribution_week'] ) ){
					$poolReportQry .= " AND `text_10`='".$_POST['distribution_week']."'";
				}
				if( !empty( $_POST['amount_due_condition'] ) && !empty( $_POST['amount_due_condition_value'] ) ){
					$amount_due_condition = $_POST['amount_due_condition'];
					if( str_contains($amount_due_condition, '>') || str_contains($amount_due_condition, '>=') || str_contains($amount_due_condition, '<') || str_contains($amount_due_condition, '<=') || str_contains($amount_due_condition, '!=') || str_contains($amount_due_condition, '=') ){
						$poolReportQry .= " AND `amount_due` ".$amount_due_condition." ".$_POST['amount_due_condition_value']."";
					}
				}
				$getTokenHolderData = $wpdb->get_row("SELECT COALESCE(SUM(`csr_amount_initial`),0) as `csr_amount_initial_total`, COALESCE(SUM(`csr_amount_issued`),0) as `csr_amount_issued_total`, COALESCE(SUM(`amount_due`),0) as `amount_due_total` FROM `$tableTokenHolder` WHERE 1 $poolReportQry");
				$data = array(
					'distribution_status'			=>	$_POST['distribution_status'],
					'pool_reference'				=>	$_POST['pool_reference'],
					'distribution_week'				=>	$_POST['distribution_week'],
					'amount_due_condition'			=>	$_POST['amount_due_condition'],
					'amount_due_condition_value'	=>	( $_POST['amount_due_condition_value'] ) ? $_POST['amount_due_condition_value'] : NULL,
					'csr_initial_amount'			=>	$getTokenHolderData->csr_amount_initial_total,
					'csr_distributed'				=>	$getTokenHolderData->csr_amount_issued_total,
					'amount_due'					=>	$getTokenHolderData->amount_due_total,
					'last_update'					=>	date_i18n( 'Y-m-d H:i:s' ),
				);
				$where = array( 'id' => $getData->id );
				$update = $wpdb->update( $tableCsrPoolReports, $data, $where );
				$updatedData = array();

				$columnArr = array('distribution_status', 'pool_reference', 'distribution_week', 'amount_due_condition', 'amount_due_condition_value', 'csr_initial_amount', 'csr_distributed', 'amount_due');
				foreach( $columnArr as $columnKey ){
					if( $data[ $columnKey ] != $getData->$columnKey ){
						$updatedData[] = sprintf( __('%s from %s to %s', CIP_TXTDOMAIN), $columnKey, $getData->$columnKey, $data[ $columnKey ] );
					}
				}
				if( empty( $updatedData ) ){
					$updatedData[] = json_encode( $data );
				}
				if( $update ){
					$logs = sprintf( __('CSR Pool Report updated by %s at %s. Details: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), implode( ', ', $updatedData ) );
					create_cip_logs_entery( $current_user->ID, 'csr_pool_report', '','sa', $logs, true );
					$out = array( "error" => 0,'msg' => __('CSR Pool Report Updated.',CIP_TXTDOMAIN) );
				}else{
					$out = array( "error" => 1,'msg' => __('Failed to Update.',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
/**
 * Refresh csr pool report
 */
add_action( 'wp_ajax_refresh_csr_pool_report_action', 'cip_refresh_csr_pool_report_action_callback' );
function cip_refresh_csr_pool_report_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		if( wp_verify_nonce( $_POST['_micro'], $user_id . md5('CIP_RefreshPoolReportData_CIP') ) ){
			$getDatas = $wpdb->get_results("SELECT * FROM $tableCsrPoolReports WHERE 1");
			$updateData = false;
			if( $getDatas ){
				foreach( $getDatas as $getData ){
					if( empty( $getData->distribution_status ) && empty( $getData->pool_reference ) && empty( $getData->distribution_week ) ){
						continue;
					}
					$poolReportQry = "";
					if( !empty( $getData->distribution_status ) ){
						$poolReportQry .= " AND `corp_approved`='".$getData->distribution_status."'";
					}
					if( !empty( $getData->pool_reference ) ){
						$poolReportQry .= " AND `pool_ref`='".$getData->pool_reference."'";
					}
					if( !empty( $getData->distribution_week ) ){
						$poolReportQry .= " AND `text_10`='".$getData->distribution_week."'";
					}
					if( !empty( $getData->amount_due_condition ) && !empty( $getData->amount_due_condition_value ) ){
						$amount_due_condition = $getData->amount_due_condition;
						if( str_contains($amount_due_condition, '>') || str_contains($amount_due_condition, '>=') || str_contains($amount_due_condition, '<') || str_contains($amount_due_condition, '<=') || str_contains($amount_due_condition, '!=') || str_contains($amount_due_condition, '=') ){
							$poolReportQry .= " AND `amount_due` ".$amount_due_condition." ".$getData->amount_due_condition_value."";
						}
					}
					$getTokenHolderData = $wpdb->get_row("SELECT COALESCE(SUM(`csr_amount_initial`),0) as `csr_amount_initial_total`, COALESCE(SUM(`csr_amount_issued`),0) as `csr_amount_issued_total`, COALESCE(SUM(`amount_due`),0) as `amount_due_total` FROM `$tableTokenHolder` WHERE 1 $poolReportQry");

					$data = array(
						'csr_initial_amount'	=>	$getTokenHolderData->csr_amount_initial_total,
						'csr_distributed'		=>	$getTokenHolderData->csr_amount_issued_total,
						'amount_due'			=>	$getTokenHolderData->amount_due_total,
						'last_update'			=>	date_i18n( 'Y-m-d H:i:s' ),
					);
					$where = array( 'id' => $getData->id );
					$update = $wpdb->update( $tableCsrPoolReports, $data, $where );

					if( $update ){
						$updateData = true;
					}else{
						$out = array( "error" => 1,'msg' => __('Failed to Refreshed.',CIP_TXTDOMAIN) );
					}
				}
				if( $updateData ){
					$logs = sprintf( __('CSR Pool Report Refreshed by %s at %s.', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
					create_cip_logs_entery( $current_user->ID, 'csr_pool_report', '','sa', $logs, true );
					$out = array( "error" => 0,'msg' => __('CSR Pool Report Refreshed.',CIP_TXTDOMAIN), 'last_update' => date_i18n( 'd/m/Y H:i A' ) );
					update_option( 'csr_pool_report_refresh', date_i18n( 'Y-m-d H:i:s' ) );
				}else{
					$out = array( "error" => 1,'msg' => __('Failed to Refreshed.',CIP_TXTDOMAIN) );
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function kyc_customize_logs_function($member_type = 'member', $type = 'KYC', $getKycData_id, $reason = '',$update_document = false,$step = 'all'){
	global $table_prefix, $wpdb;
    $current_user = wp_get_current_user();
	$user_id = $current_user->ID;
	$tableKyc = $wpdb->prefix.'kyc_data';
	$getKycData = $wpdb->get_row("SELECT * FROM $tableKyc WHERE 1 AND `id` = $getKycData_id->id AND ( `status` <> '' AND `status` IS NOT NULL )");
	$valueData = array();
	if($member_type == 'member'){
		$valueData[] = sprintf( __('Member ( %s ) submits '.strtoupper($type).' - %s', CIP_TXTDOMAIN), $getKycData->email,$getKycData->_date );
	}else{
		if($reason != ''){
			$valueData[] = sprintf( __('%s', CIP_TXTDOMAIN), $reason );
		}
	}
if($type == 'KYC'){
	if($step == 'all' || $step == 'Personal Information'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Personal Information)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; First Name - %s', CIP_TXTDOMAIN), $getKycData->firstname );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Last Name - %s', CIP_TXTDOMAIN), $getKycData->lastname );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Date Of Birth - %s', CIP_TXTDOMAIN), $getKycData->dob );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Address - %s', CIP_TXTDOMAIN), $getKycData->address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Address line 2 - %s', CIP_TXTDOMAIN), $getKycData->street_address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; City - %s', CIP_TXTDOMAIN), $getKycData->city );
		$valueData[] = sprintf( __('&nbsp;&nbsp; State / Province - %s', CIP_TXTDOMAIN), $getKycData->state );
		$valueData[] = sprintf( __('&nbsp;&nbsp; ZIP / Postal Code - %s', CIP_TXTDOMAIN), $getKycData->postal_code );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Country - %s', CIP_TXTDOMAIN), $getKycData->country );
	}
	if($step == 'all' || $step == 'Identification Document'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Identification Document)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Document Type - %s', CIP_TXTDOMAIN), $getKycData->document_type );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Document Number - %s', CIP_TXTDOMAIN), $getKycData->document_number );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Issuing Country - %s', CIP_TXTDOMAIN), $getKycData->issuing_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Issue Date - %s', CIP_TXTDOMAIN), $getKycData->issue_date );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Expiration Date - %s', CIP_TXTDOMAIN), $getKycData->expiration_date );
		// $valueData[] = sprintf( __('&nbsp;&nbsp; My document does not have expiration date. - %s', CIP_TXTDOMAIN), $getKycData->id_no_have_expiry );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Nationality - %s', CIP_TXTDOMAIN), $getKycData->nationality );
		$countDocuments = count(array_filter($update_document['identification_document']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->identification_document_1 ) && file_exists( $uploadDir.'/'.$getKycData->identification_document_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Upload' );
		}
	}
	if($step == 'all' || $step == 'Proof of Address'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Proof of Address)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Document Type - %s', CIP_TXTDOMAIN), $getKycData->document_proof );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Document Date - %s', CIP_TXTDOMAIN), $getKycData->document_date );
		$countDocuments = count(array_filter($update_document['proof_document']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->proof_document_1 ) && file_exists( $uploadDir.'/'.$getKycData->proof_document_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Identification document - %s', CIP_TXTDOMAIN), 'Upload' );
		}
	}
	if($step == 'all' || $step == 'Confirmation'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Confirmation)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Are you a politically exposed person (PEP). e.g.: Senior Military, government, political officials or relatives or associates of such officials - %s', CIP_TXTDOMAIN), $getKycData->politically_exposed_person );
		$valueData[] = sprintf( __('&nbsp;&nbsp; I consent to my data being shared with all companies in the Corsair Group - %s', CIP_TXTDOMAIN), $getKycData->consent_my_data_share );
		$valueData[] = sprintf( __('&nbsp;&nbsp; I confirm the information submitted in this form is complete and correct - %s', CIP_TXTDOMAIN), $getKycData->confirm_correct_info );
	}
}else{
	if($step == 'all' || $step == 'Business Details'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Business Details)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Business name - %s', CIP_TXTDOMAIN), $getKycData->business_name );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registration Country - %s', CIP_TXTDOMAIN), $getKycData->business_registration_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registration number - %s', CIP_TXTDOMAIN), $getKycData->business_registration_number );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Type of Business - %s', CIP_TXTDOMAIN), $getKycData->business_type_of_business );
		$valueData[] = sprintf( __('&nbsp;&nbsp; The nature of business - %s', CIP_TXTDOMAIN), $getKycData->business_nature_of_your_business );
	}
	if($step == 'all' || $step == 'Contact Details'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Registered address)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered address - %s', CIP_TXTDOMAIN), $getKycData->business_registered_address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered address line 2 - %s', CIP_TXTDOMAIN), $getKycData->business_registered_address_line_2 );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered city - %s', CIP_TXTDOMAIN), $getKycData->business_registered_city );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered state - %s', CIP_TXTDOMAIN), $getKycData->business_registered_state );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered postal code - %s', CIP_TXTDOMAIN), $getKycData->business_registered_postal_code );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Registered country - %s', CIP_TXTDOMAIN), $getKycData->business_registered_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Operatin business address)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating address - %s', CIP_TXTDOMAIN), $getKycData->business_operating_address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating address line 2 - %s', CIP_TXTDOMAIN), $getKycData->business_operating_address_line_2 );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating city - %s', CIP_TXTDOMAIN), $getKycData->business_operating_city );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating state - %s', CIP_TXTDOMAIN), $getKycData->business_operating_state );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating postal code - %s', CIP_TXTDOMAIN), $getKycData->business_operating_postal_code );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Operating country - %s', CIP_TXTDOMAIN), $getKycData->business_operating_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Additional Information)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Contact number - %s', CIP_TXTDOMAIN), $getKycData->business_contact_number );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Company website - %s', CIP_TXTDOMAIN), $getKycData->business_company_website );
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Declarations)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Are you a aware of any sanctions or embargoes that apply to your business or customers? - %s', CIP_TXTDOMAIN), $getKycData->business_aware_of_any_sanctions );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Have you undergone any external audits or assessments related to AML/CTF compilance? - %s', CIP_TXTDOMAIN), $getKycData->business_undergone_any_external_audits );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Is your business involved in any money laundering or financing of terrorism activities? - %s', CIP_TXTDOMAIN), $getKycData->business_business_involved_in_any_money_laundering );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Have you received any penalties or sanctions related to AML/CTF violations? - %s', CIP_TXTDOMAIN), $getKycData->business_received_any_penalties );
	}
	if($step == 'all' || $step == 'Director or Equivalent Person'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Business Owner)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner first name - %s', CIP_TXTDOMAIN), $getKycData->business_owner_first_name );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner last name - %s', CIP_TXTDOMAIN), $getKycData->business_owner_last_name );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner date of birth - %s', CIP_TXTDOMAIN), $getKycData->business_owner_dob );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner address - %s', CIP_TXTDOMAIN), $getKycData->business_owner_address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner address line 2 - %s', CIP_TXTDOMAIN), $getKycData->business_owner_address_line_2 );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner city - %s', CIP_TXTDOMAIN), $getKycData->business_owner_city );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner state - %s', CIP_TXTDOMAIN), $getKycData->business_owner_state );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner postal code - %s', CIP_TXTDOMAIN), $getKycData->business_owner_postal_code );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Owner country - %s', CIP_TXTDOMAIN), $getKycData->business_owner_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Is this person politically exposed? - %s', CIP_TXTDOMAIN), $getKycData->business_owner_person_politically_exposed );
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Director)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director first name - %s', CIP_TXTDOMAIN), $getKycData->business_director_first_name );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director last name - %s', CIP_TXTDOMAIN), $getKycData->business_director_last_name );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director date of birth - %s', CIP_TXTDOMAIN), $getKycData->business_director_dob );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director address - %s', CIP_TXTDOMAIN), $getKycData->business_director_address );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director address line 2 - %s', CIP_TXTDOMAIN), $getKycData->business_director_address_line_2 );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director city - %s', CIP_TXTDOMAIN), $getKycData->business_director_city );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director state - %s', CIP_TXTDOMAIN), $getKycData->business_director_state );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director postal code - %s', CIP_TXTDOMAIN), $getKycData->business_director_postal_code );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Director country - %s', CIP_TXTDOMAIN), $getKycData->business_director_country );
		$valueData[] = sprintf( __('&nbsp;&nbsp; Is this person politically exposed? - %s', CIP_TXTDOMAIN), $getKycData->business_director_person_politically_exposed );
	}
	if($step == 'all' || $step == 'Upload Documents'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Business Owner)***' ));
		$countDocuments = count(array_filter($update_document['business_certificate_of_incorporation']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_certificate_of_incorporation_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_certificate_of_incorporation_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Certificate of Incorporation/Registration of your company - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Certificate of Incorporation/Registration of your company - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Certificate of Incorporation/Registration of your company - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_shareholder_certificate']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_shareholder_certificate_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_shareholder_certificate_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Shareholder Certificate or Proof of Ownership - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Shareholder Certificate or Proof of Ownership - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Shareholder Certificate or Proof of Ownership - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_proof_address']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_proof_address_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_proof_address_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address of the Business - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address of the Business - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address of the Business - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_owner_passport_national_id']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_owner_passport_national_id_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_owner_passport_national_id_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Passport or National ID - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Passport or National ID - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Passport or National ID - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_owner_proof_address']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_owner_proof_address_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_owner_proof_address_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_director_passport_national_id']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_director_passport_national_id_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_director_passport_national_id_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Director or Equivalent Person - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Director or Equivalent Person - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Director or Equivalent Person - %s', CIP_TXTDOMAIN), 'Upload' );
		}
		$countDocuments = count(array_filter($update_document['business_director_proof_address']['name']));
		if(($countDocuments >= 1)){
			if( !empty( $getKycData->business_director_proof_address_1 ) && file_exists( $uploadDir.'/'.$getKycData->business_director_proof_address_1 ) ){
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Updated' );
			}else{
				$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Upload' );
			}
		}else{
			$valueData[] = sprintf( __('&nbsp;&nbsp; Proof of address (Personal Residential Address) - %s', CIP_TXTDOMAIN), 'Upload' );
		}
	}
	if($step == 'all' || $step == 'Confirmation'){
		$valueData[] = sprintf( __('&nbsp;&nbsp; ***(Confirmation)***' ));
		$valueData[] = sprintf( __('&nbsp;&nbsp; I consent to my data being shared with all companies in the Cosair Group - %s', CIP_TXTDOMAIN), $getKycData->consent_my_data_share );
		$valueData[] = sprintf( __('&nbsp;&nbsp; I confim the information submitted in this form is complete and correct - %s', CIP_TXTDOMAIN), $getKycData->confirm_correct_info );
	}

	}
	if($member_type != 'member'){
		$valueData[] = sprintf( __('Admin %s '.strtoupper($type).' - %s', CIP_TXTDOMAIN), ucfirst($getKycData->status), $getKycData->lastupdate );
	}
	$valueData[] = sprintf( __(''.strtoupper($type).' status saved as: %s', CIP_TXTDOMAIN), ucfirst($getKycData->status) );
	$message = implode( PHP_EOL, $valueData);
	$logs = $message;
	$userData = wp_get_current_user();
	create_cip_logs_entery( 0, 'kyc_setting', '',$member_type, $logs, true  );
}
/**
 * Generate google 2FA activation QR code image
 */
add_action('wp_ajax_google2fa_qrcode','cip_google2fa_qrcode_cb');
function cip_google2fa_qrcode_cb(){
	require_once dirname(__DIR__, 1) ."/cip-helper/phpqrcode/qrlib.php";

	QRcode::png( $_GET['qr'], false, QR_ECLEVEL_H, 4, 0, false );
	exit;
}
add_action('wp_ajax_csr_address_report_loader','csr_address_report_loader_callback');
function csr_address_report_loader_callback(){
	global $wpdb;
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
	
	$tableTokenHolder = $wpdb->prefix.'token_holder';

	$block_chain_values = explode(',', $_GET['block_chain']); // Split the comma-separated values
	$block_chain_values = array_map('esc_sql', $block_chain_values); // Sanitize values for the SQL query
	$block_chain_values = "'" . implode("','", $block_chain_values) . "'"; // Format for the IN clause
	
	$total_items = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE `eth_address` IN ($block_chain_values) GROUP BY `username`");

	$total_items = count($total_items);
		
	$filter_qry = "";
	
	$filterByConditionPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
		
	if( !empty( $filterByConditionPoolRef ) ){
		foreach( $filterByConditionPoolRef as $filterKey => $filterData ){
			if($filterData != ''){
				$filter_qry .= " AND `username` like '%" . $filterData . "%'";
			}
		}
	}

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if($filterKey == 'fullname')
			{
				$filter_qry .= " AND CONCAT(first_name, ' ', last_name) LIKE '%" . $filterData . "%'";
			}else
			{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $filter_qry");
	}
	


	if($filter_qry != ""){
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1=1 AND `eth_address` IN ($block_chain_values) GROUP BY `username` $filter_qry ");
	}
	$records = $wpdb->get_results( "SELECT * FROM $tableTokenHolder WHERE 1=1 AND `eth_address` IN ($block_chain_values) $filter_qry GROUP BY `username` ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset" );


	$rows = array();
	if( $records ){
		$rowCounter = 1;
		$count = 1;
		foreach( $records as $record ){

			$refAccount = $record->email;
			
			// $csr_balance = get_user_csr_balance( $user_id );
			$csr_balance = get_user_csr_balance( $refAccount );

			$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";


			$csrPendingResult = $wpdb->get_row("SELECT SUM(`amount_due`) as `csr_pending_total` FROM `$tableTokenHolder` WHERE $whereEmail AND ( `corp_approved`='Pending' OR `corp_approved`='Partially Delivered' ) AND `pool_ref` NOT IN('C', 'F', 'J', 'H') AND `pool_ref` NOT LIKE 'SPC%'");

			$pendingAmount = $csrPendingResult->csr_pending_total;


			$csrIssuedResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_issued_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `pool_ref`='SPC-CRSM'");
			$issuedAmount = 0;
			if( 0 ){
				$issuedAmount=$csrIssuedResult->csr_issued_total;
			}else{
				$csrIssuedResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_pending_total` FROM `$tableTokenHolder` WHERE $whereEmail AND ( `corp_approved`='Issued' OR `corp_approved`='Partially issued' )");
				$issuedAmount = $csrIssuedResult->csr_pending_total;
			}

			$csrDeliveredPendingResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_amount_delivered_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `corp_approved`='Delivered'");

			$blockchain = cip_get_ether_balance( $_GET['block_chain'] );

			$body = [
				'email'	=>	$record->email,
			];
			$response = amplivo_report_get_user_api( $body, 'get-user-data');

			$rank = '';
			$upline_usernames = array();
			$registration_date_format = "";
			if( $response['success'] == true ){
				$result = $response['result'];
				// $rank = $result['Star_1'];
				$upline_usernames = (array)$result['upline_usernames'];
				$registration_date = $result['registration_date'];
				$current_rank = $result['rank'];
				// foreach($result as $key => $star_data_item){
				// 	if(strpos($key, 'Star_') !== false ){
				// 		// $star_array[$key] = $star_data_item;
				// 		if($star_data_item != '')
				// 		{
				// 			$current_rank = trim($key, "Star_");
				// 		}
				// 	}
				// }
			}

			if( $registration_date ){
				try {
					$registration_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', $registration_date);
					$registration_date_format = $registration_date_obj->format('d/m/Y');
				} catch (\Throwable $th) {
					$registration_date_format = '—';
				}
			}

			$copyReportData = '<p class="csraddressReportContent_'.$count.'" style="display:none;">Username: 	'.$record->username.'
			Fullname: 	'.$record->first_name.' '.$record->last_name.'
			Email: 	'.$record->email.'
			Registrations Date: 	'.$registration_date_format.'
			Rank: 	'.number_format($current_rank).'
			CSR In Wallet: 	'.number_format($csr_balance).'
			CSR On Blockchain: 	'.number_format($blockchain).'
			CSR Due: 	'.number_format($pendingAmount).'
			CSR Issued: 	'.number_format($issuedAmount).'
			CSR Delivered: 	'.number_format( $csrDeliveredPendingResult->csr_amount_delivered_total ).'
			Upline To The Advisor: 	'.implode( ', ', $upline_usernames).'</p>';

			$uplone_user_ids = '<div style="white-space: nowrap;width: 300px;overflow-x: auto;">'.implode( ', ', $upline_usernames).'</div>';

			$row = array(
				'id' => $count,
				'username' => $record->username,
				'fullname' => $record->first_name.' '.$record->last_name,
				// 'description' => $record->description,
				'csr_in_wallet' => number_format($csr_balance),
				'csr_due' => number_format($pendingAmount),
				'csr_issued' => number_format($issuedAmount),
				'csr_on_blockchain' => number_format($blockchain),
				'email' => $record->email,
				'user_registrations_date' => $registration_date_format,
				'rank' => number_format($current_rank),
				'csr_delivered' => number_format( $csrDeliveredPendingResult->csr_amount_delivered_total ),
				'upline_to_the_advisor'	=>	$uplone_user_ids,
				'action'	=>	'<a class="copyReportData" data-index="'.$count.'" style="cursor: pointer;"><span class="fa fa-copy"></span></a>'.$copyReportData
			);

			$rows[] = $row;
			$rowCounter++;
			$count++;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_csr_address_report_table_data','csr_address_report_table_data_callback');
function csr_address_report_table_data_callback(){
	global $wpdb;
	
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$deliveryTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

	// $block_chain_values = explode(',', $_POST['block_chain']); // Split the comma-separated values

	$block_chain_values = array_map('esc_sql', $_POST['block_chain']); // Sanitize values for the SQL query

	// $block_chain_values = "'" . implode("','", $block_chain_values) . "'"; // Format for the IN clause
	
	$records = [];

	foreach ($block_chain_values as $address) {
		$historyRecord = $wpdb->get_results( "SELECT DISTINCT `email`, `eth_address` FROM $tableTokenHolder WHERE 1=1 AND `eth_address` = '".$address."' UNION SELECT DISTINCT `email`, `eth_address` FROM $deliveryTransactionHistory WHERE 1=1 AND `eth_address` = '".$address."'" );
		$records = [...$records,...$historyRecord];
	}

	$token = $_POST['token'];

	$rows = array();
	if( $records ){
		$rowCounter = 1;
		$count = 1;
		foreach( $records as $record ){

			$refAccount = $record->email;
			$first_name = "";
			$last_name = "";
			$username = "";
			
			// $csr_balance = get_user_csr_balance( $user_id );
			$csr_balance = get_user_csr_balance( $refAccount , 'available', strtolower($token));

			$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";


			$csrPendingResult = $wpdb->get_row("SELECT SUM(`amount_due`) as `csr_pending_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `token` = '".$token."' AND ( `corp_approved`='Pending' OR `corp_approved`='Partially Delivered' ) AND `pool_ref` NOT IN('C', 'F', 'J', 'H') AND `pool_ref` NOT LIKE 'SPC%'");

			$pendingAmount = $csrPendingResult->csr_pending_total;


			$csrIssuedResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_issued_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `token` = '".$token."' AND `pool_ref`='SPC-CRSM'");
			$issuedAmount = 0;
			if( 0 ){
				$issuedAmount=$csrIssuedResult->csr_issued_total;
			}else{
				$csrIssuedResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_pending_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `token` = '".$token."' AND ( `corp_approved`='Issued' OR `corp_approved`='Partially issued' )");
				$issuedAmount = $csrIssuedResult->csr_pending_total;
			}


			$csrDeliveredPendingResult = $wpdb->get_row("SELECT SUM(`csr_amount_issued`) as `csr_amount_delivered_total` FROM `$tableTokenHolder` WHERE $whereEmail AND `token` = '".$token."' AND `corp_approved`='Delivered'");

			
			$blockchain = cip_get_ether_balance( $record->eth_address, strtolower($token) );

			$body = [
				'email'	=>	$record->email,
			];
			$response = amplivo_report_get_user_api( $body, 'get-user-data');

			$rank = '';
			$upline_usernames = array();
			$registration_date_format = "";
			$registration_date = '';
			$current_rank = '';
			if( $response['success'] == true ){
				$result = $response['result'];
				// $rank = $result['Star_1'];
				$upline_usernames = (array)$result['upline_usernames'];
				$registration_date = $result['registration_date'];
				$current_rank = $result['rank'];
				$first_name = $result['user_first_name'];
				$last_name = $result['user_last_name'];
				$username = $result['Username'];
			}
			

			if( $registration_date ){
				try {
					$registration_date_obj = DateTime::createFromFormat('Y-m-d H:i:s', $registration_date);
					$registration_date_format = $registration_date_obj->format('d/m/Y');
				} catch (\Throwable $th) {
					$registration_date_format = '—';
				}
			}
			if($registration_date_format == '')
			{
				$registration_date_format = '-';
			}
			
			$uplines_record_str = implode( ', ', $upline_usernames);
			$uplines_record_str = ($uplines_record_str != '') ? $uplines_record_str : '-';
			$copyReportData = '<p class="csraddressReportContent_'.$count.'" style="display:none;">Username: 	'.$username.'
Full name: 	'.$first_name.' '.$last_name.'
Email: 	'.$record->email.'
Registrations Date: 	'.$registration_date_format.'
Rank: 	'.number_format($current_rank).'
'.$token.' In Wallet: 	'.number_format($csr_balance).'
'.$token.' On Blockchain: 	'.number_format($blockchain).'
'.$token.' Due: 	'.number_format($pendingAmount).'
'.$token.' Issued: 	'.number_format($issuedAmount).'
'.$token.' Delivered: 	'.number_format( $csrDeliveredPendingResult->csr_amount_delivered_total ).'
Upline To The Advisor: 	'.$uplines_record_str.'</p>';


			$copyEssentialReportData = '<p class="copyEssentialReportContent_'.$count.'" style="display:none;">Username: 	'.$username.'
Full name: 	'.$first_name.' '.$last_name.'
Email: 	'.$record->email.'
Rank: 	'.number_format($current_rank).'
Registrations Date: 	'.$registration_date_format.'
Upline To The Advisor: 	'.$uplines_record_str.'</p>';

			$uplone_user_ids = '<div style="white-space: nowrap;width: 300px;overflow-x: auto;">'.$uplines_record_str.'</div>';



			$action = '<div class="d-flex justify-content-around"><a class="copyReportData" data-index="'.$count.'" style="cursor: pointer;" title="Copy All"><span class="fa fa-copy"></span></a>'.$copyReportData;
			$action .= '<a class="copyEssentialReportData pl-2" data-index="'.$count.'" style="cursor: pointer;" title="Copy essential"><span class="fa fa-copy"></span></a>'.$copyEssentialReportData.'</div>';


			$row = array(
				'id' => $count,
				'username' => $username,
				'fullname' => $first_name.' '.$last_name,
				// 'description' => $record->description,
				'csr_in_wallet' => number_format($csr_balance),
				'csr_due' => number_format($pendingAmount),
				'csr_issued' => number_format($issuedAmount),
				'csr_on_blockchain' => number_format($blockchain),
				'email' => $record->email,
				'user_registrations_date' => $registration_date_format,
				'rank' => number_format($current_rank),
				'csr_delivered' => number_format( $csrDeliveredPendingResult->csr_amount_delivered_total ),

				'csr25_in_wallet' => number_format($csr_balance),
				'csr25_due' => number_format($pendingAmount),
				'csr25_issued' => number_format($issuedAmount),
				'csr25_on_blockchain' => number_format($blockchain),
				'csr25_delivered' => number_format( $csrDeliveredPendingResult->csr_amount_delivered_total ),				

				'upline_to_the_advisor'	=>	$uplone_user_ids,
				'action'	=>	$action
			);

			$rows[] = $row;
			$rowCounter++;
			$count++;
		}
	}
	$out = array(
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
/**
 * function to fetch amplivo api response
 */
function amplivo_api_send_requests( $body = [], $endpoint = "" ){
	$amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
	$amplivo_api_test_source_url = ( !empty( get_option('amplivo_api_test_source_url') ) ) ? get_option('amplivo_api_test_source_url') : 'https://cloudhorizon.sandbox.jox.hu/api/';
	$amplivo_api_live_source_url = ( !empty( get_option('amplivo_api_live_source_url') ) ) ? get_option('amplivo_api_live_source_url') : 'https://amplivo.com/api/';
	$amplivo_api_auth_username = ( !empty( get_option('amplivo_api_auth_username') ) ) ? get_option('amplivo_api_auth_username') : 'amplivoapiuser';
	$amplivo_api_auth_pwd = ( !empty( get_option('amplivo_api_auth_pwd') ) ) ? get_option('amplivo_api_auth_pwd') : 'fdlkg948ty89gh498rghuv';
	$sourceApiUrl = ( $amplivo_api_mode == 'live' ) ? $amplivo_api_live_source_url : $amplivo_api_test_source_url;
	$body = wp_json_encode( $body );
	$authorization = 'Basic ' . base64_encode( $amplivo_api_auth_username . ':' . $amplivo_api_auth_pwd );
	$response = wp_remote_post( $sourceApiUrl . $endpoint, array(
		'method' 	=> 'POST',
		'headers'	=> array(
			'accept'		=>	'application/json',
			'Authorization'		=>	$authorization,
			'content-type'	=>	'application/json',
		),
		'body' 		=> $body,
	) );
	if ( ! is_wp_error( $response ) ) {
		$bodyResponse = json_decode( wp_remote_retrieve_body( $response ), true );
	}else{
		$error_message = $response->get_error_message();
		$bodyResponse = json_decode( '{"success":false,"error":"'.$error_message.'"}', true );
	}
	return $bodyResponse;
}
/**
 * function to fetch report get user api
 */
function amplivo_report_get_user_api( $body = [], $endpoint = "" ){
	$amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
	$amplivo_api_test_source_url = ( !empty( get_option('amplivo_api_test_source_url') ) ) ? get_option('amplivo_api_test_source_url') : 'https://cloudhorizon.sandbox.jox.hu/api/';
	$amplivo_api_live_source_url = ( !empty( get_option('amplivo_api_live_source_url') ) ) ? get_option('amplivo_api_live_source_url') : 'https://amplivo.com/api/';
	$amplivo_report_user_api_url = ( !empty( get_option('amplivo_report_user_api_url') ) ) ? get_option('amplivo_report_user_api_url') : 'https://amplivo.com/api/';
	$amplivo_api_auth_username = ( !empty( get_option('amplivo_api_auth_username') ) ) ? get_option('amplivo_api_auth_username') : 'amplivoapiuser';
	$amplivo_api_auth_pwd = ( !empty( get_option('amplivo_api_auth_pwd') ) ) ? get_option('amplivo_api_auth_pwd') : 'fdlkg948ty89gh498rghuv';
	// $sourceApiUrl = $amplivo_report_user_api_url ? $amplivo_report_user_api_url : 'https://console-amplivo.corsair-development.com/api/';
	$sourceApiUrl = 'https://console-amplivo.corsair-development.com/api/';
	$body = wp_json_encode( $body );
	$authorization = 'Basic ' . base64_encode( $amplivo_api_auth_username . ':' . $amplivo_api_auth_pwd );
	$response = wp_remote_post( $sourceApiUrl . $endpoint, array(
		'method' 	=> 'POST',
		'headers'	=> array(
			'accept'		=>	'application/json',
			'Authorization'		=>	$authorization,
			'content-type'	=>	'application/json',
		),
		'body' 		=> $body,
	) );
	if ( ! is_wp_error( $response ) ) {
		$bodyResponse = json_decode( wp_remote_retrieve_body( $response ), true );
	}else{
		$error_message = $response->get_error_message();
		$bodyResponse = json_decode( '{"success":false,"error":"'.$error_message.'"}', true );
	}
	return $bodyResponse;
}
//MA enabled update code
add_action('wp_ajax_load_selected_plastic_credit_type_table','load_selected_plastic_credit_type_table_cb');
function load_selected_plastic_credit_type_table_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if(isset($_POST['plastic_credit_type']) && $_POST['plastic_credit_type'] != '' ){
		global $wpdb;
		$tableName = $wpdb->prefix.'token_holder';
		$tableNameCol = $wpdb->prefix.'token_holder_columns';
		$tableRetirement = $wpdb->prefix.'retirement_data';
		$refAccount = $_SESSION['refAccount'];
		if( (isset( $_GET['fromdate'] ) && isset( $_GET['todate'] )) && (!empty( $_GET['fromdate'] ) && !empty( $_GET['todate'] )) ){
			$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE email = '".$refAccount."' AND ( ( STR_TO_DATE(redemption_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_GET['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(redemption_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_GET['todate'] . "', '%d/%m/%Y') ) OR ( STR_TO_DATE(claim_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_GET['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(claim_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_GET['todate'] . "', '%d/%m/%Y') ) ) ");
		}else{
			$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE email = '".$refAccount."' AND eth_address <> '' GROUP BY eth_address ");
		}
		global $defaultColumnsArr;

		$getMembersColumns = $wpdb->get_row("SELECT * FROM $tableNameCol WHERE email = '".$refAccount."' ");

		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsTHColumnOption = (array)get_option('cip_column_th_toggle_columns');
		$columnsTHToggleArr = (array)maybe_unserialize( $getMembersColumns->columns );
		$columnsArr = array();
		if( !empty( $columnsTHToggleArr ) ){
			if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsTHToggleArr[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}else{
			if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsTHColumnOption[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}
		ob_start();
			?>
			
			<table id="tokenholder_table_retirment" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="true" data-show-export="false" class="table table-bordered">
				<thead>
					<tr>
						<th data-field="id" class="id" data-switchable="false"><?php _e('Id',CIP_TXTDOMAIN); ?></th>
						<th data-field="plastic_credit" class="plastic_credit" data-switchable="false"><?php _e('Plastic Credit',CIP_TXTDOMAIN); ?></th>
						<th data-field="eth_address" data-sortable="false" data-switchable="false" class="eth_address"><?php _e('CSR Wallet Address',CIP_TXTDOMAIN); ?> <?php echo cipColumnHeaderTooltip( __('External CSR Wallet address for CSR distribution', CIP_TXTDOMAIN) ); ?></th>
						<th data-field="eth_balance" class="eth_balance" data-sortable="false" data-switchable="false"><?php _e('Balance',CIP_TXTDOMAIN); ?> <?php echo cipColumnHeaderTooltip( __('Amount of CSR in the External CSR wallet address available for retirement', CIP_TXTDOMAIN) ); ?></th>
						<th data-field="action" class="action" data-switchable="false"><?php _e('Action',CIP_TXTDOMAIN); ?> <?php echo cipColumnHeaderTooltip( __('Actions that can be performed with this External CSR wallet address', CIP_TXTDOMAIN) ); ?></th>
					</tr>
				</thead>
				<tbody>
				<?php
				$countLoop = 1;
				foreach( $getCurrentMembers as $getCurrentMember ){
					$importedUserData = get_userdata( $getCurrentMember->imported_by );
					$is_edit_eth = false;

					$encryptToken = base64_encode( $getCurrentMember->id . md5( $_POST['plastic_credit_type'] ));

					?><tr data-eth="<?php echo $getCurrentMember->id; ?>" data-tokenType="<?php echo strtolower( $_POST['plastic_credit_type'] ); ?>" data-token="<?php echo $encryptToken; ?>"  >
						<td><?php echo $countLoop; ?></td>
						<td><?php echo $_POST['plastic_credit_type']; ?></td>
						<?php
						if( !empty( $getCurrentMember->eth_address ) ){
							$columnsDataValMask = substr($getCurrentMember->eth_address, 0, 6) . '...' . substr($getCurrentMember->eth_address, -6);
							$columnsDataVal = '<a href="https://etherscan.io/address/'. $getCurrentMember->eth_address . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$getCurrentMember->eth_address.'" >'.$columnsDataValMask.'</a>';
							if( $getCurrentMember->sign_verify == 1 ){
								$columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />';
							}
						}else{
							$is_edit_eth = true;
							$columnsDataVal = '—';
						}

						$save_link = "";
						$verify_link = "";
						$unsave_link = "";
						if( $getCurrentMember->sign_verify == 1 && !empty( $getCurrentMember->saved_amount ) && empty( $getCurrentMember->saving_start_date ) ){
							$unsave_link = '<a href="javascript:void(0);" class="cip_unsave_csr mr-2 ml-2"><i class="fas fa-undo" data-toggle-tt="tooltip" data-placement="top" title="'.__('Cancel your save request',CIP_TXTDOMAIN).'"></i></a>';
						}
						$eth_balance = cip_get_ether_balance( $getCurrentMember->eth_address, $_POST['plastic_credit_type'] );
						$retirment_tooltip = __('My retirements',CIP_TXTDOMAIN);
						if( !is_numeric( $eth_balance ) || $eth_balance <= 0 ){
							$retirment_tooltip = sprintf( __('No CSR at blockchain address %s',CIP_TXTDOMAIN), $getCurrentMember->eth_address );
						}
						$retirement_class = "";
						if( is_numeric( $eth_balance ) && $eth_balance > 0 ){
							$retirement_class = "eth_retirement_btn " . strtolower( $_POST['plastic_credit_type'] );
						}
						$viewRetirement = '';
						$totalRetirement = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE email = '".$refAccount."' AND token = '".$_POST['plastic_credit_type']."' AND eth_address = '".$getCurrentMember->eth_address."' ");
						$totalRetirementConfirmCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE email = '".$refAccount."' AND token = '".$_POST['plastic_credit_type']."' AND eth_address = '".$getCurrentMember->eth_address."' AND retire_status = 1 ");
						if( $totalRetirement ){
							$viewRetirement = '<a class="fa fa-eye mr-2 ml-2 viewRetirementDetail" plastic_credit="'.$_POST['plastic_credit_type'].'" href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title=" '. __('View retirements',CIP_TXTDOMAIN) . '"></a>';
						}

						$totalRetirementPdfLink = "";
						if( $totalRetirementConfirmCount ){
							$pdf_url = add_query_arg( array(
								'retireaddress'	=>	$getCurrentMember->eth_address,
								'plastic_credit'	=>	$_POST['plastic_credit_type'],
								'action' => 'total_retire_pdf',
							), admin_url('admin-ajax.php') );
							$totalRetirementPdfLink = '<a class="fa fa-download mr-2 ml-2 viewRetirementTotal" href="'.$pdf_url.'" target="_blank" data-toggle-tt="tooltip" data-placement="top" title=" '. __('Total retirements',CIP_TXTDOMAIN) . '"></a>';
						}

						?>
						<td class="eth_address"><?php echo $columnsDataVal; ?></td>
						<td><?php if (fmod($eth_balance, 1) !== 0.0) { echo number_format( $eth_balance, 2 ); }else{ echo number_format( $eth_balance ); } ?></td>
						<td>
							<?php echo $verify_link; ?>
							<?php if( $getCurrentMember->sign_verify == 1 ){ ?>
								<a class="fa fa-wallet mr-2 ml-2 <?php echo $retirement_class; ?>" href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="left" title="<?php echo $retirment_tooltip; ?>"></a>
							<?php }else{ ?>
								<a href="javascript:void(0);" class="signVerifyBtn mr-2 ml-2" data-toggle-tt="tooltip" data-placement="top" title="<?php echo __('Verify your CSR Wallet address using MetaMask (Free).',CIP_TXTDOMAIN); ?>"><i class="fas fa-user-check"></i></a>
							<?php } ?>
							<?php echo $viewRetirement; ?>
							<?php echo $totalRetirementPdfLink; ?>
						</td>
					</tr><?php
					$countLoop++;
				}
				?>
				</tbody>
			</table>
			<div class="modal fade" id="chooseRetireAmount" tabindex="-1" role="dialog" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered" role="document">
					<div class="modal-content">
						<div class="modal-body">

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

			<div class="modal fade" id="showRetireDetails" tabindex="-1" role="dialog" aria-hidden="true" style="font-family: 'Montserrat';">
				<div class="modal-dialog modal-dialog-centered modal-xl text-left" role="document">
					<div class="modal-content">
						<div class="modal-body">

						</div>
					</div>
				</div>
			</div>
		<?php
		$html = ob_get_clean();
		$out = array( "error" => 0,'html' => $html );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_get_token_Balance_withdraw','cip_get_token_Balance_withdraw_cb');
function cip_get_token_Balance_withdraw_cb(){
	$token = $_POST['token'];
	$current_user = wp_get_current_user();
    $user_email = $current_user->user_email;

	$csr_amount = get_user_csr_balance( $user_email, '', $token);
	$percentageNumber25 = ( $csr_amount * 25 ) / 100;
	$percentageNumber50 = ( $csr_amount * 50 ) / 100;
	$percentageNumber75 = ( $csr_amount * 75 ) / 100;
	$percentageNumber100 = ( $csr_amount * 100 ) / 100;

	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$availableBalance = get_user_csr_balance( $user_email, 'available',  $token);

	$out = array( "error" => 0, "percentageNumber25" => $percentageNumber25, "percentageNumber50" => $percentageNumber50, "percentageNumber75" => $percentageNumber75, "percentageNumber100" => $percentageNumber100, 'availableBalance' => number_format($availableBalance));

	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_order_process_action','cip_order_process_action_cb');
function cip_order_process_action_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['micro'],'_CIPxOrderProcessCIP_' ) && current_user_can( 'supportagent' ) ){
		$specific_id = $_POST['id'];
		global $wpdb;
		$current_user = wp_get_current_user();
		$wpdb_prefix = $wpdb->prefix;
		$invoice= $wpdb_prefix.'cip_member_invoice';
		$PackagesTable = $wpdb->prefix . 'sa_packages';
		$invoice_data = $wpdb->get_row($wpdb->prepare( "SELECT * FROM `$invoice` WHERE `id` = %d", $specific_id),ARRAY_A);
		$email = $invoice_data['Email'];
		$email = $invoice_data['Email'];
		$Order_ID = $invoice_data['ProformaInvoiceNumber'];
		$Order_Amount = $invoice_data['ProductPrice'];
		$Order_Name = $invoice_data['FirstName']." ".$invoice_data['LastName'];
		$Order_BusinessName = $invoice_data['BusinessName'];
		$Order_IntroducedBy = $invoice_data['IntroducedBy'];
		$Order_Status = $invoice_data['Status'];
		$body = ['email'	=>	$email];
		$orderID = base64_encode($specific_id);
		$response = amplivo_api_send_requests( $body, 'get-user-data');
		$no_user_found = false;
		if( $response['success'] == true && strpos($invoice_data['Username'], 'CSRCorpBuyer') === false){
			$result = $response['result'];
			$UserStatus = $result['Status'];
			$Username = $result['Username'];
			$sponsorbody = ['username'	=>	$result['sponsor_username']];
			$sponsorresponse = amplivo_api_send_requests( $sponsorbody, 'get-user-data');
			if( $sponsorresponse['success'] == true ){
				$sponsorresult = $sponsorresponse['result'];
				$SUsername = $sponsorresult['Username'];
				$S_name = $sponsorresult['user_full_name'];
				$Semail = $sponsorresult['Email'];
			}
			if($UserStatus == 'active' || $UserStatus == 'abandoned' || $Order_Status == 'Incomplete' ){
				if($UserStatus == 'abandoned' && $Order_Status != 'Incomplete' ){
					$body = [
                        'username'	=>	$Username,
                        'status'	=>	'active',
                    ];
                    $UpdateProfileresponse = amplivo_api_send_requests( $body, 'update-profile');
					if( $UpdateProfileresponse['success'] == true ){
						$logs = sprintf( __('Amplivo profile status for Amplivo user (%s) with order ID (%s) has been changed from "abandoned" to "active" by %s at %s', CIP_TXTDOMAIN), $email, $Order_ID, $current_user->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( $current_user->ID, 'Update amplivo Profile', '','sa', $logs, true );
						$body = [
							'username'	=>	$Username,
							'kycStatus' =>  0,
							"kycReason" => "Reactive User"
						];
						$UpdateKYCStatus = amplivo_api_send_requests( $body, 'update-kyc-status');
						if( $UpdateKYCStatus['success'] == true ){
							$logs = sprintf( __('Amplivo profile KYC status for Amplivo user (%s) with order ID (%s) has been changed from "active" to "drop" by %s at %s', CIP_TXTDOMAIN), $email, $Order_ID, $current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery( $current_user->ID, 'Update amplivo Profile', '','sa', $logs, true );
							$UpdateProfileresult = $UpdateProfileresponse['data'];
							$UserStatus = $UpdateProfileresult['status'];
							$body = [
								'username'	=>	$Username
							];
							$GetOCABalance = amplivo_api_send_requests( $body, 'get-oca-balance');
							if( $GetOCABalance['success'] == true ){
								if($GetOCABalance['result'] != null && $GetOCABalance['result'] != 0){
									$UserOCABalance = abs($GetOCABalance['result']);
									$body = [
										'username'		=>	$Username,
										'amount'    	=> ( $GetOCABalance['result'] > 0 ) ? '-'.$UserOCABalance : $UserOCABalance,
										'description' 	=> "Clean User OCA"
									];
									$CleanOCABalance = amplivo_api_send_requests( $body, 'update-oca-balance');
									if( $CleanOCABalance['success'] == true ){
										$logs = sprintf( __('Amplivo OCA balance for Amplivo User (%s) with order ID (%s) has been cleared by %s at %s', CIP_TXTDOMAIN), $email, $Order_ID, $current_user->user_email, date_i18n('d/m/Y H:i A') );
										create_cip_logs_entery( $current_user->ID, 'Update amplivo Profile', '','sa', $logs, true );
									}else{
										$logs = sprintf( __('Failed to Clear OCA balance for Amplivo User (%s) by %s at %s', CIP_TXTDOMAIN), $email, $current_user->user_email, date_i18n('d/m/Y H:i A') );
										create_cip_logs_entery( $current_user->ID, 'Failed Update amplivo Profile', '','sa', $logs, true );
									}
									$out = array( "error" => 0, 'msg' => 'active');
								}else{
									$out = array( "error" => 0, 'msg' => 'active');
								}
							}else{
								$logs = sprintf( __('Failed to Get OCA balance for Amplivo User (%s) by %s at %s', CIP_TXTDOMAIN), $email, $current_user->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery( $current_user->ID, 'Failed Update amplivo Profile', '','sa', $logs, true );
								$out = array( "error" => 1, 'msg' => $UpdateKYCStatus['error'] );
							}
						}else{
							$logs = sprintf( __('Failed to Update Amplivo profile KYC status for Amplivo user (%s) by %s at %s', CIP_TXTDOMAIN), $email, $current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery( $current_user->ID, 'Failed Update amplivo Profile', '','sa', $logs, true );
							$out = array( "error" => 1, 'msg' => $GetOCABalance['error'] );
						}
					}else{
						$logs = sprintf( __('Failed to Update Amplivo profile for Amplivo user (%s) by %s at %s', CIP_TXTDOMAIN), $email, $current_user->user_email, date_i18n('d/m/Y H:i A') );
						create_cip_logs_entery( $current_user->ID, 'Failed Update amplivo Profile', '','sa', $logs, true );
						$out = array( "error" => 1, 'msg' => $UpdateProfileresponse['error'] );
					}
				}else{
					$out = array( "error" => 0, 'msg' => 'active');
				}
			}else{
				$out = array( "error" => 1, 'msg' => 'User Status is not active' );
			}
		}else{
			$no_user_found = true;
			$Username = 'CSRCorpBuyer'.$Order_ID;
			// $email = 'csrcorpbuyer+'.$Order_ID.'@gmail.com';
			$checkuserexistbody = ['username'	=>	$Username];

			$_SESSION['CorpBuyerUsername'] = $Username;
			$_SESSION['CorpBuyerEmail'] = $email;
			if($Order_Status != 'Incomplete'){
				$checkuserexistresponse = amplivo_api_send_requests( $checkuserexistbody, 'get-user-data');
				if( $checkuserexistresponse['success'] == true ){
					session_start();
					$suffix = 1;
					$baseUsername = 'CSRCorpBuyer' . $Order_ID;
					// $baseEmail = 'csrcorpbuyer+' . $Order_ID;
					do {
						// Create the username and email with the current suffix
						$Username = $baseUsername . str_pad($suffix, 2, '0', STR_PAD_LEFT);
						// $email = $baseEmail . str_pad($suffix, 2, '0', STR_PAD_LEFT) . '@gmail.com';
					
						// Check if the username exists
						$checkuserexistbody = ['username' => $Username];
						$checkuserexistresponse = amplivo_api_send_requests($checkuserexistbody, 'get-user-data');
					
						// Increment suffix if username exists
						$suffix++;
					} while ($checkuserexistresponse['success'] == true);
					$_SESSION['CorpBuyerUsername'] = $Username;
					$_SESSION['CorpBuyerEmail'] = $email;
				}
			}else{
				$Username = $invoice_data['Username'];
				preg_match('/(\D+)(\d+)/', $Username, $matches);
				if (count($matches) === 3) {
					$namePart = strtolower($matches[1]);
					$numberPart = $matches[2];
					// $email = $namePart . '+' . $numberPart . '@gmail.com';
				}
			}
			$amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
			if($Order_IntroducedBy == '' || strtolower( $Order_IntroducedBy ) == strtolower( 'Amplivo' ) ){
				if($amplivo_api_mode == 'test'){
					$Order_IntroducedBy = 'Amplivotestaccount1';
				}else{
					$Order_IntroducedBy = 'Amplivo';
				}
			}
			$sponsorbody = ['username'	=>	$Order_IntroducedBy];
			$sponsorresponse = amplivo_api_send_requests( $sponsorbody, 'get-user-data');
			if( $sponsorresponse['success'] == true ){
				$sponsorresult = $sponsorresponse['result'];
				$SUsername = $sponsorresult['Username'];
				$S_name = $sponsorresult['user_full_name'];
				$Semail = $sponsorresult['Email'];
			}
			$out = array( "error" => 0, 'msg' => 'active','data' => $sponsorresponse,'Order_IntroducedBy' => $Order_IntroducedBy );
		}
		$html = "";
		ob_start();
		?>
		<form name="order_prosess_request_wizard" class="order_prosess_request_wizard" id="msform">
		<!-- progressbar -->
		 	<?php 
			if($invoice_data['Status'] == 'Incomplete'){
				$check_box_checked = true;
				$tab_nav_style = "width:16%;";
			}else{
				$check_box_checked = false;
				$tab_nav_style = "width: 20%;";
			}
			?>
			<ul id="progressbar" class="mb-3">
				<li class="active" id="fieldmapping" style="<?php echo $tab_nav_style; ?>"><strong><?php _e('Step-1','corsair-login') ?></strong></li>
				<li id="fieldmapping" style="<?php echo $tab_nav_style; ?>" ><strong><?php _e('Step-2','corsair-login') ?></strong></li>
				<li id="fieldmapping" style="<?php echo $tab_nav_style; ?>"><strong><?php _e('Step-3','corsair-login') ?></strong></li>
				<li id="fieldmapping" style="<?php echo $tab_nav_style; ?>"><strong><?php _e('Step-4','corsair-login') ?></strong></li>
				<li id="fieldmapping" style="<?php echo $tab_nav_style; ?>"><strong><?php _e('Step-5','corsair-login') ?></strong></li>
				<?php 
				if($invoice_data['Status'] == 'Incomplete'){
				?>
				<li id="fieldmapping"><strong><?php _e('Step-6','corsair-login') ?></strong></li>
				<?php 
				}
				?>
			</ul>
			<div class="progress">
				<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="<?php echo $tab_nav_style; ?>"></div>
			</div>
			<br> <!-- fieldsets -->
			<fieldset class="step_0">
				<div class="form-card">
					<div class="row">
						<div class="col-12">
							<p class="steps" style="text-align:left !important;"><?php echo sprintf('Step - %s %s', 1, ($check_box_checked) ? '(Completed)' : ''); ?></p>
						</div>
					</div>
					<?php 
						if($no_user_found){
					?>
					<div class="list-flex">
						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="phantom_user_check" name="phantom_user_check" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
							<label class="custom-control-label pt-1" for="phantom_user_check"><?php
							echo sprintf( __('Create a phantom account on Amplivo:<br><br>
							Username: %s<br><br>
							Email: %s<br><br>
							Name: %s<br><br>
							Sponsor: %s<br><br>
							No email confirmation will be sent. Email will be set to confirmed.', CIP_TXTDOMAIN), $Username, $email, $Order_Name, $Order_IntroducedBy );
						?></label>
						</div>
					</div>
					<?php
						}
					?>
					<div class="list-flex">
						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="user_uploaded_oca_check" name="user_uploaded_oca_check" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
							<label class="custom-control-label pt-1" for="user_uploaded_oca_check"><?php echo sprintf( __('Upload %s Euros to %s OCA balance.', CIP_TXTDOMAIN), cip_number_format($Order_Amount), $Username ); ?></span></label>
						</div>
					</div>

					<div class="list-flex">
						<div class="custom-control custom-checkbox mb-3">
							<input type="checkbox" class="custom-control-input" id="purchase-note" name="purchase-note" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
							<label class="custom-control-label pt-1" for="purchase-note"><?php echo sprintf( __('Purchase PNPs with a total value of %s Euros.', CIP_TXTDOMAIN),cip_number_format($Order_Amount)); ?></label>
						</div>
					</div>

					<p class="notes-text"><b>Note: </b> this is the Price from the PO and not the Total Payable.. sometimes these are the same, but often the price is less.</p>

					<div class="custom-control custom-checkbox mb-3">
						<input type="checkbox" class="custom-control-input" id="gift_redeem" name="gift_redeem" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
						<label class="custom-control-label pt-1" for="gift_redeem"><?php echo sprintf( __('Redeem automatically the gift code(s) for %s.', CIP_TXTDOMAIN),$Username); ?></label>
					</div>
										
				<input type="button" name="next" class="next_OI action-button" value="Next" />
			</fieldset>

			<fieldset class="step_1">
				<div class="form-card">
					<div class="row">
						<div class="col-12">
							<p class="steps"  style="text-align:left !important;"><?php echo sprintf('Step - %s %s', 2,($check_box_checked) ? '(Completed)' : ''); ?></p>
						</div>
						<div class="text-left col-12">
							<div class="custom-control custom-checkbox mb-3">
								<input type="checkbox" class="custom-control-input" id="ticket_raised_checkbox" name="ticket_raised_checkbox" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
								<?php
									if($no_user_found){
										?>
										<label class="custom-control-label pt-1" for="ticket_raised_checkbox"><?php echo sprintf( __('An email will be sent from noreply@csrnow.com to buyers email.', CIP_TXTDOMAIN)); ?></label>
										<?php
									}else{
										?>
										<label class="custom-control-label pt-1" for="ticket_raised_checkbox"><?php echo sprintf( __('A ticket will be raised to the  %s.', CIP_TXTDOMAIN),$Username); ?></label>
										<?php
									}
								?>
							</div>
						</div>
						<div class="text-left col-12">
						<?php
							if($no_user_found){
								?>
									<p class="mail-content">
										Dear Supporter,<br><br>

										Thank you for purchasing a Plastic Neutrality Package!<br><br>

										Your order CSR-PO-<?php echo $Order_ID;?> has been successfully processed.<br><br>

										Please allow up to 7 days for your purchase to appear on CSRnow. To access your account, log in using your email address.<br><br>

										For assistance with https://CSRNow.com , please reach out to the individual who introduced you to CSR.<br><br>

										We appreciate your support in helping us advance our mission to rid the planet of plastic waste.<br><br>

										Thank you!
									</p>
								<?php
							}else{
								?>
								
									<p class="mail-content">Dear member,<br/><br/>
										Thank you for purchasing a Plastic Neutrality Package!<br/><br/>
										Your order CSR-PO-<?php echo $Order_ID;?> has been successfully processed.<br><br>
										Please allow up to 7 days for your purchase to appear on CSRnow. To access your account, log in using your email address.<br/><br/>
										We appreciate your support in helping us advance our mission to rid the planet of plastic waste.<br/><br/>
										Thank you!<br/>
									</p>
								<?php
							}
						?>
						</div>
					</div>
				</div>

				<input type="button" name="next" class="next_OI action-button" value="Next" />
				<input type="button" name="previous" class="previous_OI action-button-previous" value="Previous" />
			</fieldset>

			<fieldset class="step_2">
			<div class="form-card">
				<div class="row">
					<div class="col-12">
						<p class="steps" style="text-align:left !important;"><?php echo sprintf('Step - %s %s', 3,($check_box_checked) ? '(Completed)' : ''); ?></p>
					</div>
					<div class="col-12 mb-2">
						<div class="list-flex">
							<div class="custom-control custom-checkbox">
								<input type="checkbox" class="custom-control-input" id="user_upline_notified_check" name="user_upline_notified_check" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
								<label class="custom-control-label pt-1" for="user_upline_notified_check"><?php echo sprintf( __('Members sponsor ( username: %s, name: %s, email address: %s ) will be notified of the purchase.', CIP_TXTDOMAIN), $SUsername,$S_name,$Semail); ?></label>
							</div>
						</div>
					</div>
					<div class="col-12 mb-3">
						<?php
						if($no_user_found){
							?>
								<p class="notes-text"><b>Note: </b> If sponsor is Amplivo, this ticket will not be created..</p>
							<?php
						}
						?>
					</div>
					<div class="row text-left p-3">
					<div class="col-12 mb-3">
						<?php
							if($no_user_found){
								?>
									<p class="mail-content">Dear Member,<br><br>

										This ticket was generated automatically in relation to a Plastic Neutrality Package purchase completed by an individual or a company with the email address <?php echo $invoice_data['Email']; ?>.<br><br>

										This purchase has been assigned to your 1st line in the Amplivo Network.<br><br>

										Please reach out to your referral if they need any assistance logging into https://CSRnow.com.<br><br>

										Please allow up to 7 days for the purchase to appear on CSRnow.<br/>
									</p>
								<?php
							}else{
								?>
								
								<p class="mail-content">Dear member,<br/><br/>
									This ticket was generated automatically in relation to a Plastic Neutrality Package purchase completed by an individual or a company with the email address <?php echo $invoice_data['Email']; ?>.<br/><br/>
									This purchase has been assigned to your 1st line in the Amplivo Network.<br/><br/>
									Please reach out to your referral if they need any assistance logging into https://CSRnow.com.<br/><br/>
									Please allow up to 7 days for the purchase to appear on CSRnow.<br/>
								</p>
								<?php
							}
						?>
					</div>
					<div class="col-12">
						<div class="list-flex">
							<div class="custom-control custom-checkbox mb-3">
								<input type="checkbox" class="custom-control-input" id="user_po_marked_check" name="user_po_marked_check" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
								<label class="custom-control-label pt-1" for="user_po_marked_check"><?php echo sprintf( __('The PO will be marked as paid and archived on CSRnow. (You can view
	archived rows as needed.).', CIP_TXTDOMAIN) ); ?></span></label>
							</div>
						</div>
					</div>
					</div>
				</div>
			
				<div class="row justify-content-center">
					<h5 class="update_withdraw_request_response"></h5>
				</div>
			</div>
			<input type="button" name="next" class="next_OI action-button" value="Next" />
			<input type="button" name="previous" class="previous_OI action-button-previous" value="Previous" />
			</fieldset>

			<fieldset class="step_3">
				<div class="form-card">
					<div class="row">
						<?php 
						if($invoice_data['Status'] != 'Incomplete'){
							?>
							<div class="col-12">
								<p class="steps" style="text-align:left !important;"><?php echo sprintf('Step - %s', 4, $total_step); ?></p>
								<div class="otp_section pb-3">
									<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
									<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
									<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
								</div>
							</div>
							<?php
						}else{
							?>
							<div class="col-12">
								<p class="steps" style="text-align:left !important;"><?php echo sprintf('Step - %s', 4, $total_step); ?></p>
								<div class="otp_section pb-3">
									<?php 
										foreach(json_decode($invoice_data['total_steps'], true) as $key => $Incomplete_item ){
											if($Incomplete_item['complate_step']){
												?>
												<div class="Incomplete_item"><?php echo $Incomplete_item['complate_message']; ?></div>
												<?php
											}else{
												if($Incomplete_item['type'] == 'create_user'){
													$process_step = 'Amplivo Phantom username: '.$Incomplete_item['Username'].' create';
												}
												if($Incomplete_item['type'] == 'order_create'){
													$process_step = 'CSR-PO-'.$Order_ID.' order for '.$Incomplete_item['amount'].' Euros created.';
												}
												if($Incomplete_item['type'] == 'add_oca_balance'){
													$process_step = $Incomplete_item['amount'].' Euros uploaded to '.$Incomplete_item['Username'].' OCA wallet';
												}
												if(str_starts_with($Incomplete_item['type'], 'purchase_item') || str_starts_with($Incomplete_item['type'], 'purchase_redeem_item')){
													$PackagesData = $wpdb->get_row(
														$wpdb->prepare(
															"SELECT packageid, heading 
															 FROM $PackagesTable 
															 WHERE active = 1 AND euro_amount = %d", 
															$Incomplete_item['product_amount']
														),
														ARRAY_A
													);
													$packageid = $PackagesData['packageid'];
													$PackagesName = $PackagesData['heading'];
													if(str_starts_with($Incomplete_item['type'], 'purchase_item')){
														$process_step = 'Product '.$PackagesName.' Purchase';
													}
													if(str_starts_with($Incomplete_item['type'], 'purchase_redeem_item')){
														$process_step = 'Product '.$PackagesName.' Redeem';
													}
												}
												if($Incomplete_item['type'] == 'create_user_ticket'){
													$process_step = "Ticket to ".$Incomplete_item['Username'];
												}
												if($Incomplete_item['type'] == 'create_Sponsor_ticket'){
													$process_step = "Ticket to Sponsor ".$Incomplete_item['Username'];
												}
												if($Incomplete_item['type'] == 'purchased_mail_to_member'){
													$process_step = "Mail to ".$Incomplete_item['email'];
												}
												if($Incomplete_item['type'] == 'purchased_ticket_to_sponsor'){
													$process_step = "Ticket to Sponsor ".$Semail;
												}
												if($Incomplete_item['type'] == 'update_order_status'){
													$process_step = "Invoice CSR-xxxx create (Pending)<br>";
													$process_step .= "CSR-PO-".$Order_ID." status set to Paid and archived";
												}
												?>
													<div class="Incomplete_item"><?php echo $process_step; ?> (Pending)</div>
												<?php
											}
										}
									?>
								</div>
							</div>
							<div class="col-12">
								<div class="list-flex">
									<div class="custom-control custom-checkbox mb-3">
										<input type="checkbox" class="custom-control-input" id="user_complate_po_process_check" name="user_complate_po_process_check" <?php echo ($check_box_checked) ? 'checked disabled' : '' ; ?> required>
										<label class="custom-control-label pt-1" for="user_complate_po_process_check"><?php echo sprintf( __('Proceed with completion of the purchase.', CIP_TXTDOMAIN) ); ?></span></label>
									</div>
								</div>
							</div>
							<?php
						}
						?>
					</div>
				</div>
				<input type="button" name="next" class="next_OI action-button" value="Next" />
				<input type="button" name="previous" class="previous_OI action-button-previous" value="Previous" />
			</fieldset>
			
			<fieldset class="step_4">
				<?php 
					if($invoice_data['Status'] == 'Incomplete'){
						?>
						<div class="form-card">
							<div class="col-12">
								<p class="steps" style="text-align:left !important;"><?php echo sprintf('Step - %s', 5, $total_step); ?></p>
								<div class="otp_section pb-3">
									<label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>
									<input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />
									<small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
								</div>
							</div>
						</div>
						<input type="button" name="next" class="next_OI action-button" value="Next" />
						<input type="button" name="previous" class="previous_OI action-button-previous" value="Previous" />
						<?php
					}else{
						?>
						<div class="form-card">
							<div class="row">
								<div class="purchase_responce" style="height: 400px;">
								</div>
							</div>
						</div>
						<input type="button" name="close" class="withdrawal_close_btn action-button-previous  close" data-dismiss="modal" id="close_op_process" style="display:none;" value="close" />
						<?php
					}
				?>
			</fieldset>
			<?php 
			if($invoice_data['Status'] == 'Incomplete'){
			?>
			<fieldset class="step_5">
				<div class="form-card">
					<div class="row">
						<div class="purchase_responce" style="height: 400px;">
						</div>
					</div>
				</div>
				<input type="button" name="close" class="withdrawal_close_btn action-button-previous  close" data-dismiss="modal" id="close_op_process" style="display:none;" value="close" />
			</fieldset>
			<?php
			}
			?>
			
			<input type="hidden" name="action" value="sa_order_request_wizard_action" />
			<input type="hidden" name="id" id="order_id" value="<?php echo $orderID;?>" />
			<input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPorderRequestWizardCIP_'); ?>" />
		</form>
		<?php
		$html .= ob_get_clean();
		if($out['error'] == 0){
			$out['html'] = $html;
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sa_order_request_wizard_action','sa_order_request_wizard_action_cb');
function sa_order_request_wizard_action_cb(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$specific_id = base64_decode($_POST['id']);
	global $wpdb;
	$current_user = wp_get_current_user();
	$wpdb_prefix = $wpdb->prefix;
	$invoice= $wpdb_prefix.'cip_member_invoice';
	$PackagesTable = $wpdb->prefix . 'sa_packages';
	session_start();
	if( wp_verify_nonce( $_POST['_micro'],'_CIPorderRequestWizardCIP_' ) && current_user_can( 'supportagent' ) ){
		$invoice_data = $wpdb->get_row($wpdb->prepare( "SELECT * FROM `$invoice` WHERE `id` = %d", $specific_id),ARRAY_A);
		$email = $invoice_data['Email'];
		$Order_ID = $invoice_data['ProformaInvoiceNumber'];
		$amount = $invoice_data['ProductPrice'];
		$Order_Name = $invoice_data['FirstName']." ".$invoice_data['LastName'];
		$Order_IntroducedBy = $invoice_data['IntroducedBy'];
		$Order_BusinessName = $invoice_data['BusinessName'];
		
		if( $_POST['step'] == 4){
			$gaOTPValid = false;
			$google_auth_key = get_user_meta( $current_user->ID, 'google_auth_key', true );
			if( !empty( $_POST['user_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}
			if($gaOTPValid == false){
				$out = array( "error" => 1, 'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$amount = $invoice_data['ProductPrice'];
			$products = getpackages();
			
			
			[$ProductID, $purchaseOption, $remainingAmount] = findPurchaseOption($amount, $products);
			$body = ['email'	=>	$email];
			$response = amplivo_api_send_requests( $body, 'get-user-data');
			$step_to_do = array();
			if( $response['success'] == true ){
				$result = $response['result'];
				$Username = $result['Username'];
			}else{

				$Username = 'CSRCorpBuyer'.$Order_ID;
				$checkuserexistbody = ['username'	=>	$Username];
				$checkuserexistresponse = amplivo_api_send_requests( $checkuserexistbody, 'get-user-data');
				if( $checkuserexistresponse['success'] == true ){
					$Username = $_SESSION['CorpBuyerUsername'];
					unset($_SESSION['CorpBuyerUsername']);
					unset($_SESSION['CorpBuyerEmail']);
				}

				$step_to_do[] = array(
					"type" => "create_user",
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
			}
			$splitAmounts = splitAmount($amount);
			foreach($splitAmounts as $splitAmount){
				$step_to_do[] = array(
					"type" => "add_oca_balance",
					"Username" => $Username,
					"email" => $email,
					"amount" => $splitAmount,
					"complate_step" => false
				);
			}
			$step_to_do[] = array(
				"type" => "order_create",
				"Username" => $Username,
				"email" => $email,
				"amount" => $amount,
				"complate_step" => false
			);
			$i = 0;
			foreach($remainingAmount as $Productitem){
				$step_to_do[] = array(
					"type" => 'purchase_item'.$i,
					'product_amount' => $Productitem,
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
				$step_to_do[] = array(
					"type" => 'purchase_redeem_item'.$i,
					'product_amount' => $Productitem,
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
				$i++;
			}
			if( $response['success'] == true ){
				$step_to_do[] = array(
					"type" => 'create_user_ticket',
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
				$step_to_do[] = array(
					"type" => 'create_Sponsor_ticket',
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
			}else{
				$step_to_do[] = array(
					"type" => 'purchased_mail_to_member',
					"Username" => $Username,
					"email" => $email,
					"complate_step" => false
				);
				if($Order_IntroducedBy != '' && strtolower( $Order_IntroducedBy ) != strtolower( 'Amplivo' ) ){
					$step_to_do[] = array(
						"type" => 'purchased_ticket_to_sponsor',
						"Username" => $Username,
						"email" => $email,
						"complate_step" => false
					);
				}
			}
			$step_to_do[] = array(
				"type" => "update_order_status",
				"Username" => $Username,
				"email" => $email,
				"complate_step" => false
			);
			$update_data = array(
				'Status' => 'Incomplete',
				'total_steps' => json_encode($step_to_do)
			);
			
			$update_where = array(
				'id' => $specific_id
			);
			
			$updated_rows = $wpdb->update(
				$invoice,
				$update_data,
				$update_where,
				array('%s', '%s'),
				array('%d')
			);
			if($updated_rows){
				$out = array( "error" => 0 );
			}
			
		}else if(	$_POST['step'] == 'check_authentication'){
			$gaOTPValid = false;
			$google_auth_key = get_user_meta( $current_user->ID, 'google_auth_key', true );
			if( !empty( $_POST['user_ga_otp'] ) ){
				$google2fa = new \PragmaRX\Google2FA\Google2FA();
				if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
					$gaOTPValid = true;
				}
			}
			if($gaOTPValid == false){
				$out = array( "error" => 1, 'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
				echo wp_json_encode( $out );
				exit;
			}
			$complated_process = "";
			$Order_total_steps = json_decode($invoice_data['total_steps'], true);
			if (!empty($Order_total_steps) && is_array($Order_total_steps)) {
				foreach ($Order_total_steps as $Order_total_step_key => $Order_total_step_value) {
					if (!empty($Order_total_step_value['complate_step']) && $Order_total_step_value['complate_step'] == true) {
						$POprocess_log	= strip_tags($Order_total_step_value['complate_message']);
						if (strpos($POprocess_log, "OCA walletCSR-PO") !== false) {
							$POprocess_log = str_replace("OCA walletCSR-PO-", "OCA wallet<br><br>CSR-PO-", $POprocess_log);
						}
						$_SESSION['POprocess_log'][] = strip_tags($POprocess_log);
						$complated_process .= $Order_total_step_value['complate_message'];
					}
				}
				$_SESSION['POprocess_log'][] = "Upper process is already done";
			}
			$out = array( "error" => 0, "complated_process" => $complated_process );

		}else if( $_POST['step'] == 5){

			$Order_total_steps = json_decode($invoice_data['total_steps'], true);
			$complate = true;
			foreach($Order_total_steps as $Order_total_step_key => $Order_total_step_value){
				if($Order_total_step_value['complate_step'] == false){

					$stepRun = 'step run : ' . $Order_total_step_value['type'];
					create_cip_logs_entery( $current_user->ID, 'step_run', '','sa', $stepRun, true );

					if($Order_total_step_value['type'] == "create_user"){
						$amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
						if($Order_IntroducedBy == '' || strtolower( $Order_IntroducedBy ) == strtolower( 'Amplivo' ) ){
							if($amplivo_api_mode == 'test'){
								$Order_IntroducedBy = 'Amplivotestaccount1';
							}else{
								$Order_IntroducedBy = 'Amplivo';
							}
						}
						$sponsorbody = ['username'	=>	$Order_IntroducedBy];
						$sponsorresponse = amplivo_api_send_requests( $sponsorbody, 'get-user-data');
						if( $sponsorresponse['success'] == true ){
							$sponsorresult = $sponsorresponse['result'];
							$SUsername = $sponsorresult['Username'];
							$Username = $Order_total_step_value['Username'];
							$email = $Order_total_step_value['email'];
							$checkuserexistbody = ['username'	=>	$Username];
							$checkuserexistresponse = amplivo_api_send_requests( $checkuserexistbody, 'get-user-data');
							$body = [
								'username'			=> $Username,
								'password'    		=> substr(str_shuffle('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 9) . rand(0, 9),
								'email' 			=> $email,
								'sponsor_username' 	=> $SUsername,
								'firstname' 		=> $invoice_data['FirstName'],
								'lastname' 			=> $invoice_data['LastName'],
								'is_email_verified' => 1,
							];
							
							$CreatedPentamUser = amplivo_api_send_requests( $body, 'new-user');
							if( $CreatedPentamUser['success'] == true ){
								$message = sprintf( __('<div>Amplivo Phantom username: %s created.</div>', CIP_TXTDOMAIN), $Username );
								$out = array( "error" => 0, 'message' => $message);
								$logs = sprintf( __('Amplivo Phantom username: %s created by %s at %s. Response:%s', CIP_TXTDOMAIN), $Username, $current_user->user_email, date_i18n('d/m/Y H:i A'),json_encode($CreatedPentamUser) );
								$_SESSION['POprocess_log'][] = $logs;
								$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
								$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
								$update_data = array(
									'Status' => 'Incomplete',
									'Username' => $Username,
									'total_steps' => json_encode($Order_total_steps)
								);
								
								$update_where = array(
									'id' => $specific_id
								);
								
								$updated_rows = $wpdb->update(
									$invoice,
									$update_data,
									$update_where,
									array('%s', '%s', '%s'),
									array('%d')
								);
								$out = array( "error" => 0, 'message' => $message);
								echo wp_json_encode( $out );
								exit;
							}else{
								$message = sprintf( __('<div class="text-danger">Failed to Created Amplivo Phantom username: %s</div>', CIP_TXTDOMAIN), $Username );
								$logs = sprintf( __('Failed to Created Amplivo Phantom username: %s created by %s at %s. Response:%s', CIP_TXTDOMAIN), $Username, $current_user->user_email, date_i18n('d/m/Y H:i A'),json_encode($CreatedPentamUser) );
								create_cip_logs_entery( $current_user->ID, 'Create Amplivo User', '','sa', $logs, true );
								$out = array( "error" => 1, 'msg' => $CreatedPentamUser['error'], 'message' => $message );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$message = sprintf( __('<div class="text-danger">Failed to Created Amplivo Phantom username: %s</div>', CIP_TXTDOMAIN), $Order_total_step_value['Username'] );
							$logs = sprintf( __('Failed to Created Amplivo Phantom username: %s created by %s at %s. Response:%s', CIP_TXTDOMAIN), $Order_total_step_value['Username'], $current_user->user_email, date_i18n('d/m/Y H:i A'),json_encode($sponsorresponse) );
							create_cip_logs_entery( $current_user->ID, 'Create Amplivo User', '','sa', $logs, true );
							$out = array( "error" => 1, 'msg' => $sponsorresponse['error'], 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if($Order_total_step_value['type'] == "add_oca_balance"){
						$Order_ID = $invoice_data['ProformaInvoiceNumber'];
						$body = ['username'	=>	$Order_total_step_value['Username']];
						$response = amplivo_api_send_requests( $body, 'get-user-data');
						if( $response['success'] == true ){
							$result = $response['result'];
							$Username = $result['Username'];
							$UserEmail = $result['Email'];
							$body = [
								'username'		=>	$Username,
								'amount'    	=> $Order_total_step_value['amount'],
								'description' 	=> "CSR-PO-".$Order_ID." purchase"
							];
							$CleanOCABalance = amplivo_api_send_requests( $body, 'update-oca-balance');
							if( $CleanOCABalance['success'] == true ){
								$message = sprintf( __('<div>%s Euros uploaded to %s OCA wallet</div>', CIP_TXTDOMAIN), cip_number_format($Order_total_step_value['amount']), $Username  );
								$logs = sprintf( __('%s Euros uploaded to %s OCA wallet. Response:%s', CIP_TXTDOMAIN), cip_number_format($Order_total_step_value['amount']), $Username,json_encode($CleanOCABalance) );
								$_SESSION['POprocess_log'][] = $logs;
								$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
								$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
								$update_data = array(
									'Status' => 'Incomplete',
									'total_steps' => json_encode($Order_total_steps)
								);
								
								$update_where = array(
									'id' => $specific_id
								);
								
								$updated_rows = $wpdb->update(
									$invoice,
									$update_data,
									$update_where,
									array('%s', '%s'),
									array('%d')
								);
								$out = array( "error" => 0, 'message' => $message);
								echo wp_json_encode( $out );
								exit;
							}else{
								$message = sprintf( __('<div class="text-danger">Failed to Update OCA.</div>', CIP_TXTDOMAIN) );
								$logs = sprintf( __('Failed to Update OCA username: %s created by %s at %s. Response:%s', CIP_TXTDOMAIN), $Username, $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode($CleanOCABalance));
								$out = array( "error" => 1, 'msg' => $CleanOCABalance['error'], 'message' => $message );
								create_cip_logs_entery( $current_user->ID, 'Update OCA Amplivo User', '','sa', $logs, true );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$message = sprintf( __('<div class="text-danger">Failed to Update OCA.</div>', CIP_TXTDOMAIN) );
							$logs = sprintf( __('Failed to Update OCA username: %s created by %s at %s. Response:%s', CIP_TXTDOMAIN), $Order_total_step_value['Username'], $current_user->user_email, date_i18n('d/m/Y H:i A'), json_encode($response));
							$out = array( "error" => 1, 'msg' => $response['error'], 'message' => $message );
							create_cip_logs_entery( $current_user->ID, 'Update OCA Amplivo User', '','sa', $logs, true );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if($Order_total_step_value['type'] == "order_create"){
						$Order_ID = $invoice_data['ProformaInvoiceNumber'];
						$message = sprintf( __('<div>CSR-PO-%s order for %s Euros created.</div>', CIP_TXTDOMAIN), $Order_ID, cip_number_format($amount) );
						$logs = sprintf( __('CSR-PO-%s order for %s Euros created.', CIP_TXTDOMAIN), $Order_ID, cip_number_format($amount) );
						$_SESSION['POprocess_log'][] = $logs;
						$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
						$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
						$update_data = array(
							'Status' => 'Incomplete',
							'total_steps' => json_encode($Order_total_steps)
						);
						
						$update_where = array(
							'id' => $specific_id
						);
						
						$updated_rows = $wpdb->update(
							$invoice,
							$update_data,
							$update_where,
							array('%s', '%s'),
							array('%d')
						);
						$out = array( "error" => 0, 'message' => $message);
						echo wp_json_encode( $out );
						exit;
					}
					if(strpos($Order_total_step_value['type'], 'purchase_item') === 0){
						$message = '';
						$PackagesData = $wpdb->get_row(
							$wpdb->prepare(
								"SELECT packageid, heading 
								 FROM $PackagesTable 
								 WHERE active = 1 AND euro_amount = %d", 
								$Order_total_step_value['product_amount']
							),
							ARRAY_A
						);
						$packageid = $PackagesData['packageid'];
						$PackagesName = $PackagesData['heading'];
						$body = [
							'username'		=>	$Order_total_step_value['Username'],
							'packageid'    	=> 	$packageid,
						];
						$purchase_responce = amplivo_api_send_requests( $body, 'purchase');
						if( $purchase_responce['success'] == true ){
							$Usernamebody = ['username'	=>	$Order_total_step_value['Username']];
							$Usernameresponse = amplivo_api_send_requests( $Usernamebody, 'get-user-data');
							if( $Usernameresponse['success'] == true ){
								$Usernameresult = $Usernameresponse['result'];
								$getUsername = $Usernameresult['Username'];
								$getEmail = $Usernameresult['Email'];
								$getuser_full_name = $Usernameresult['user_full_name'];
							}
							$message = "<div>Product ".$PackagesName." Purchased</div>";
							$logs = sprintf( __('Product %s Purchased. Response:%s', CIP_TXTDOMAIN), $PackagesName,json_encode($purchase_responce));
							$_SESSION['POprocess_log'][] = $logs;
							$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
							$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
							$Order_total_steps[($Order_total_step_key+1)]['gitcode'] = $purchase_responce['result'];
							$Order_total_steps[($Order_total_step_key+1)]['product_id'] = $packageid;
							$update_data = array(
								'Status' => 'Incomplete',
								'total_steps' => json_encode($Order_total_steps)
							);
							
							$update_where = array(
								'id' => $specific_id
							);
							
							$updated_rows = $wpdb->update(
								$invoice,
								$update_data,
								$update_where,
								array('%s', '%s'),
								array('%d')
							);
							$out = array( "error" => 0, 'message' => $message);
							echo wp_json_encode( $out );
							exit;
						}else{
							$message = sprintf( __('<div class="text-danger">Failed to Purchased product(%s).</div>', CIP_TXTDOMAIN), $PackagesName );
							$logs = sprintf( __('Failed to Purchased product(%s) Response:%s', CIP_TXTDOMAIN), $PackagesName, json_encode($purchase_responce));
							$_SESSION['POprocess_log'][] = $logs;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => $purchase_responce['error'], 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(strpos($Order_total_step_value['type'], 'purchase_redeem_item') === 0){
						$message = '';
						$body = [
							'username'		=>	$Order_total_step_value['Username'],
							'giftcode'    	=> 	$Order_total_step_value['gitcode'],
						];
						$PackagesName = $wpdb->get_var(
							$wpdb->prepare("SELECT heading FROM $PackagesTable WHERE active = 1 AND packageid = %d", $Order_total_step_value['product_id'])
						);
						$redeem_responce = amplivo_api_send_requests( $body, 'redeem-gift-code');
						if( $redeem_responce['success'] == true ){
							$message = "<div>Product ".$PackagesName." Redeemed.</div>";
							$logs = sprintf( __('Product %s redeemed. Response:%s', CIP_TXTDOMAIN), $PackagesName, json_encode($redeem_responce));
							$_SESSION['POprocess_log'][] = $logs;
							$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
							$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
							$update_data = array(
								'Status' => 'Incomplete',
								'total_steps' => json_encode($Order_total_steps)
							);
							
							$update_where = array(
								'id' => $specific_id
							);
							
							$updated_rows = $wpdb->update(
								$invoice,
								$update_data,
								$update_where,
								array('%s', '%s'),
								array('%d')
							);
							$out = array( "error" => 0, 'message' => $message);
							echo wp_json_encode( $out );
							exit;
						}else{
							$message = sprintf( __('<div class="text-danger">Failed to Redeemed Product(%s).</div>', CIP_TXTDOMAIN), $PackagesName );
							$logs = sprintf( __('Failed to Redeemed Product(%s) Response:%s', CIP_TXTDOMAIN), $PackagesName,json_encode($redeem_responce));
							$_SESSION['POprocess_log'][] = $logs;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => $redeem_responce['error'], 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(	$Order_total_step_value['type'] == 'purchased_mail_to_member'){
						$membermessage = sprintf( __("<p><b>Dear Supporter</b>,</p>

						<p>Thank you for purchasing a Plastic Neutrality Package!</p>

						<p>Your order CSR-PO-%s has been successfully processed.</p>

						<p>Please allow up to 7 days for your purchase to appear on CSRnow. To access your account, log in using your email address.</p>

						<p>For assistance with https://CSRNow.com , please reach out to the individual who introduced you to CSR.</p>

						<p>We appreciate your support in helping us advance our mission to rid the planet of plastic waste.</p>

						<p>Thank you!</p>", CIP_TXTDOMAIN), $Order_ID );
						$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@csrnow.com'; } );
						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( $membermessage );
						$subject = ' Plastic Neutrality Package purchase';
						$sent_mail = wp_mail( $email, $subject, $htmlContent );
						if( $sent_mail ){
							$message = "<div>Mail to ".$email." sent.</div>";
							$logs = sprintf( __('Mail to %s sent.', CIP_TXTDOMAIN),$email);
							$_SESSION['POprocess_log'][] = $logs;
							$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
							$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
							$update_data = array(
								'Status' => 'Incomplete',
								'total_steps' => json_encode($Order_total_steps)
							);
							
							$update_where = array(
								'id' => $specific_id
							);
							
							$updated_rows = $wpdb->update(
								$invoice,
								$update_data,
								$update_where,
								array('%s', '%s'),
								array('%d')
							);
							$out = array( "error" => 0, 'message' => $message);
							echo wp_json_encode( $out );
							exit;
						}else{
							$message = sprintf( __('<div class="text-danger">Failed to send Member Purchasing mail (%s)</div>', CIP_TXTDOMAIN),$email);
							$logs = sprintf( __('Failed to send Member Purchasing mail (%s)', CIP_TXTDOMAIN),$email);
							$_SESSION['POprocess_log'][] = $logs;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => 'Failed to send Member Purchasing mail', 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(	$Order_total_step_value['type'] == 'purchased_ticket_to_sponsor'){
						$amplivo_api_mode = ( !empty( get_option('amplivo_api_mode') ) ) ? get_option('amplivo_api_mode') : 'test';
						if($Order_IntroducedBy == '' || strtolower( $Order_IntroducedBy ) == strtolower( 'Amplivo' ) ){
							if($amplivo_api_mode == 'test'){
								$Order_IntroducedBy = 'Amplivotestaccount1';
							}else{
								$Order_IntroducedBy = 'Amplivo';
							}
						}
						$support_mode = ( !empty( get_option('cip_support_ticket_mode') ) ) ? get_option('cip_support_ticket_mode') : 'disable';
						$endpoint_url = '';
						if( $support_mode == 'live' ){
							$endpoint_url = 'https://amplivo.com/api/support/create';
						}else if( $support_mode == 'test' ){
							$endpoint_url = 'https://cloudhorizon.sandbox.jox.hu/api/support/create';
						}else{		
							$endpoint_url = '';
						}
						$sponsorbody = ['username'	=>	$Order_IntroducedBy];
						$sponsorresponse = amplivo_api_send_requests( $sponsorbody, 'get-user-data');
						if( $sponsorresponse['success'] == true ){
							$sponsorresult = $sponsorresponse['result'];
							$Username = $sponsorresult['Username'];
							$SEmail = $sponsorresult['Email'];
							$user_full_name = $result['user_full_name'];
							$membermessage = sprintf( __('Dear Member,

							This ticket was generated automatically in relation to a Plastic Neutrality Package purchase completed by an individual or a company with the email address %s.

							This purchase has been assigned to your 1st line in the Amplivo Network.
							Please reach out to your referral if they need any assistance logging into https://CSRnow.com.

							Please allow up to 7 days for the purchase to appear on CSRnow.
							', CIP_TXTDOMAIN), $email );
							$body = array(
								'email' => $SEmail,
								'subject' => 'Plastic Neutrality Package purchase',
								'message' => $membermessage,
								'language' => 'en-GB',
								'name' => $user_full_name,
								'category' => 2090,
								'status' => 100,
							);
							$create_responce = wp_remote_post( $endpoint_url, array(
								'method' 	=> 'POST',
								'body' 		=> $body,
							) );
							if ( ! is_wp_error( $create_responce ) ) {
								$create_responce_body = json_decode($create_responce['body']);
								$message = "<div>Ticket to Sponsor ".$Username." created.</div>";
								$logs = sprintf( __('Ticket to Sponsor %s created Response:%s.', CIP_TXTDOMAIN),$Username,$create_responce['body'] );
								$_SESSION['POprocess_log'][] = $logs;
								$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
								$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
								$update_data = array(
									'Status' => 'Incomplete',
									'total_steps' => json_encode($Order_total_steps)
								);
								
								$update_where = array(
									'id' => $specific_id
								);
								
								$updated_rows = $wpdb->update(
									$invoice,
									$update_data,
									$update_where,
									array('%s', '%s'),
									array('%d')
								);
								$out = array( "error" => 0, 'message' => $message);
								echo wp_json_encode( $out );
								exit;
							}else{
								$message = "<div class='text-danger'>Failed Ticket created for Sponsor(".$Username.").</div>";
								$logs = sprintf( __('Failed Ticket created for Sponsor(%s) Response:%s', CIP_TXTDOMAIN), $Username,$create_responce['body'] );
								$_SESSION['POprocess_log'][] = $logs;
								$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
								$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
								unset($_SESSION['POprocess_log']);
								$out = array( "error" => 1, 'msg' => 'Failed Ticket created for Sponsor('.$Username.')', 'message' => $message );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$message = "<div class='text-danger'>Failed Ticket created for Sponsor(".$Order_IntroducedBy.").</div>";
							$logs = sprintf( __('Failed Ticket created for Sponsor(%s) Response:%s', CIP_TXTDOMAIN), $Order_IntroducedBy,json_encode($sponsorresponse) );
							$_SESSION['POprocess_log'][] = $logs;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => 'Failed Ticket created for Sponsor('.$Order_IntroducedBy.')', 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(	$Order_total_step_value['type'] == 'create_user_ticket'){
						$body = ['username'	=>	$Order_total_step_value['Username']];
						$response = amplivo_api_send_requests( $body, 'get-user-data');
						$support_mode = ( !empty( get_option('cip_support_ticket_mode') ) ) ? get_option('cip_support_ticket_mode') : 'disable';
						$endpoint_url = '';
						if( $support_mode == 'live' ){
							$endpoint_url = 'https://amplivo.com/api/support/create';
						}else if( $support_mode == 'test' ){
							$endpoint_url = 'https://cloudhorizon.sandbox.jox.hu/api/support/create';
						}else{		
							$endpoint_url = '';
						}
						$update_to_paid = false;
						if( $response['success'] == true ){
							$result = $response['result'];
							$Username = $result['Username'];
							$user_full_name = $result['user_full_name'];
							$sponsor_username = $result['sponsor_username'];
							$Email = $result['Email'];
							$membermessage = sprintf( __('Dear Member,

							Thank you for purchasing a Plastic Neutrality Package!

							Your order CSR-PO-%s has been successfully processed.

							Please allow up to 7 days for your purchase to appear on CSRnow. To access your account, log in using your email address.

							We appreciate your support in helping us advance our mission to rid the planet of plastic waste.

							Thank you!
							', CIP_TXTDOMAIN), $Order_ID );
							$body = array(
								'email' => $Email,
								'subject' => 'Plastic Neutrality Package purchase',
								'message' => $membermessage,
								'language' => 'en-GB',
								'name' => $user_full_name,
								'category' => 2090,
								'status' => 100,
							);
							$create_responce = wp_remote_post( $endpoint_url, array(
								'method' 	=> 'POST',
								'body' 		=> $body,
							) );
							if ( ! is_wp_error( $create_responce ) ) {
								$create_responce_body = json_decode($create_responce['body']);
								$message = "<div>Ticket to ".$Username." created.</div>";
								$logs = sprintf( __('Ticket to %s created Response:%s.', CIP_TXTDOMAIN),$Username,$create_responce['body'] );
								$_SESSION['POprocess_log'][] = $logs;
								$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
								$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
								$update_data = array(
									'Status' => 'Incomplete',
									'total_steps' => json_encode($Order_total_steps)
								);
								
								$update_where = array(
									'id' => $specific_id
								);
								
								$updated_rows = $wpdb->update(
									$invoice,
									$update_data,
									$update_where,
									array('%s', '%s'),
									array('%d')
								);
								$out = array( "error" => 0, 'message' => $message);
								echo wp_json_encode( $out );
								exit;
							}else{
								$message = "<div class='text-danger'>Failed Ticket created for USER(".$Username.").</div>";
								$logs = sprintf( __('Failed Ticket created for USER(%s) Response:%s', CIP_TXTDOMAIN), $Username,$create_responce['body'] );
								$_SESSION['POprocess_log'][] = $logs;
								$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
								$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
								unset($_SESSION['POprocess_log']);
								$out = array( "error" => 1, 'msg' => 'Failed Ticket created for USER('.$Username.')', 'message' => $message );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$message = "<div class='text-danger'>Failed Ticket created for USER(".$Order_total_step_value['Username'].").</div>";
							$logs = sprintf( __('Failed Ticket created for USER(%s) Response:%s', CIP_TXTDOMAIN), $Order_total_step_value['Username'],json_encode($response) );
							$_SESSION['POprocess_log'][] = $logs;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => 'Failed Ticket created for USER('.$Order_total_step_value['Username'].')', 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(	$Order_total_step_value['type'] == 'create_Sponsor_ticket'){
						$body = ['username'	=>	$Order_total_step_value['Username']];
						$response = amplivo_api_send_requests( $body, 'get-user-data');
						$support_mode = ( !empty( get_option('cip_support_ticket_mode') ) ) ? get_option('cip_support_ticket_mode') : 'disable';
						$endpoint_url = '';
						if( $support_mode == 'live' ){
							$endpoint_url = 'https://amplivo.com/api/support/create';
						}else if( $support_mode == 'test' ){
							$endpoint_url = 'https://cloudhorizon.sandbox.jox.hu/api/support/create';
						}else{		
							$endpoint_url = '';
						}
						$update_to_paid = false;
						if( $response['success'] == true ){
							$result = $response['result'];
							$Username = $result['Username'];
							$user_full_name = $result['user_full_name'];
							$sponsor_username = $result['sponsor_username'];
							$Email = $result['Email'];
							$sponsorbody = ['username'	=>	$sponsor_username];
							$sponsorresponse = amplivo_api_send_requests( $sponsorbody, 'get-user-data');
							if( $sponsorresponse['success'] == true ){
								$sponsorresult = $sponsorresponse['result'];
								$sponsorUsername = $sponsorresult['Username'];
								$sponsoruser_full_name = $sponsorresult['user_full_name'];
								$sponsorEmail = $sponsorresult['Email'];
								$sponsormessage = sprintf( __('Dear Member,

								This ticket was generated automatically in relation to a Plastic Neutrality Package purchase completed by an individual or a company with the email address %s.

								This purchase has been assigned to your 1st line in the Amplivo Network.

								Please reach out to your referral if they need any assistance logging into https://CSRnow.com.

								Please allow up to 7 days for the purchase to appear on CSRnow.
								', CIP_TXTDOMAIN), $email );
								$sponsorbody = array(
									'email' => $sponsorEmail,
									'subject' => 'Plastic Neutrality Package purchase',
									'message' => $sponsormessage,
									'language' => 'en-GB',
									'name' => $sponsoruser_full_name,
									'category' => 2090,
									'status' => 100,
								);
								$sponsorcreate_responce = wp_remote_post( $endpoint_url, array(
									'method' 	=> 'POST',
									'body' 		=> $sponsorbody,
								) );
								if ( ! is_wp_error( $sponsorcreate_responce ) ) {
									$sponsorcreate_responce_body = json_decode($sponsorcreate_responce['body']);
									$message = "<div>Ticket to Sponsor ".$sponsorUsername." created.</div>";
									$logs = sprintf( __('Ticket to Sponsor %s created.  Response:%s', CIP_TXTDOMAIN),$sponsorUsername,$sponsorcreate_responce['body'] );
									$_SESSION['POprocess_log'][] = $logs;
									$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
									$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
									$update_data = array(
										'Status' => 'Incomplete',
										'total_steps' => json_encode($Order_total_steps)
									);
									
									$update_where = array(
										'id' => $specific_id
									);
									
									$updated_rows = $wpdb->update(
										$invoice,
										$update_data,
										$update_where,
										array('%s', '%s'),
										array('%d')
									);
									$out = array( "error" => 0, 'message' => $message);
									echo wp_json_encode( $out );
									exit;
								}else{
									$message = "<div class='text-danger'>Failed Ticket Created for sponsor(".$sponsorUsername.").</div>";
									$logs = sprintf( __('Failed Ticket Created for sponsor(%s). Response:%s', CIP_TXTDOMAIN),$sponsorUsername,$sponsorcreate_responce['body'] );
									$_SESSION['POprocess_log'][] = $logs;
									$update_to_paid = false;
									$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
									$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
									create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
									unset($_SESSION['POprocess_log']);
									$out = array( "error" => 1, 'msg' => 'Failed Ticket created for sponsor('.$sponsorUsername.')', 'message' => $message );
									echo wp_json_encode( $out );
									exit;
								}
							}else{
								$message = "<div class='text-danger'>Failed Ticket Created for sponsor(".$sponsorUsername.").</div>";
								$logs = sprintf( __('Failed Ticket Created for sponsor(%s). Response:%s', CIP_TXTDOMAIN),$sponsorUsername,json_encode($sponsorresponse) );
								$_SESSION['POprocess_log'][] = $logs;
								$update_to_paid = false;
								$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
								$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
								unset($_SESSION['POprocess_log']);
								$out = array( "error" => 1, 'msg' => 'Failed Ticket created for sponsor('.$sponsorUsername.')', 'message' => $message );
								echo wp_json_encode( $out );
								exit;
							}
						}else{
							$message = "<div class='text-danger'>Failed Ticket Created for sponsor.</div>";
							$logs = sprintf( __('Failed Ticket Created for sponsor. Response:%s', CIP_TXTDOMAIN),json_encode($response) );
							$_SESSION['POprocess_log'][] = $logs;
							$update_to_paid = false;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => 'Failed Ticket created for sponsor('.$sponsorUsername.')', 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
					if(	$Order_total_step_value['type'] == 'update_order_status'){

						$paidDate= date_i18n( 'd-m-Y');
						$invoiceRecordMaxQry = "SELECT * FROM $invoice WHERE `Status` = 'Paid' ORDER BY `InvoiceNumber` DESC";
						$invoiceRecordMaxRecord = $wpdb->get_row($invoiceRecordMaxQry);
						if( $invoiceRecordMaxRecord ){ 
							$InvoiceNumber = $invoiceRecordMaxRecord->InvoiceNumber + 1;
						}else{
							$InvoiceNumber = 1001;
						}

						$update_data = array(
							'ArchiveStatus' => 'Yes',
							'Status' => 'Paid',
							'PaidDate' => $paidDate,
							'InvoiceNumber' => $InvoiceNumber,
						);
						
						$update_where = array(
							'id' => $specific_id
						);
						
						$updated_rows = $wpdb->update(
							$invoice,
							$update_data,
							$update_where,
							array('%s', '%s', '%s', '%d'),
							array('%d')
						);
						if ($updated_rows > 0) {
							if (isset($_SESSION['POprocess_log'])) {
								$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
								$combined_logs .= sprintf( __('<br><br>Invoice CSR-%s created.', CIP_TXTDOMAIN), $InvoiceNumber );
								$combined_logs .= sprintf( __('<br><br>CSR-PO-%s status set to Paid and archived.', CIP_TXTDOMAIN), $Order_ID );
								$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
								create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
								unset($_SESSION['POprocess_log']);
							}
							$message = "<div>Invoice CSR-".$InvoiceNumber." created.</div>";
							$message .= "<div>CSR-PO-".$Order_ID." status set to Paid and archived.</div>";
							$Order_total_steps[$Order_total_step_key]['complate_step'] = true;
							$Order_total_steps[$Order_total_step_key]['complate_message'] = $message;
							$update_data = array(
								'total_steps' => json_encode($Order_total_steps)
							);
							
							$update_where = array(
								'id' => $specific_id
							);
							
							$updated_rows = $wpdb->update(
								$invoice,
								$update_data,
								$update_where,
								array('%s'),
								array('%d')
							);
							$out = array( "error" => 0, 'message' => $message,'isComplete' => true);
							echo wp_json_encode( $out );
							exit;
						}else{
							$message = "<div class='text-danger'>Failed to CSR-PO-".$Order_ID." status set to Paid and archived.</div>";
							$logs = sprintf( __('CSR-PO-'.$Order_ID.' status set to Paid and archived.', CIP_TXTDOMAIN) );
							$_SESSION['POprocess_log'][] = $logs;
							$update_to_paid = false;
							$combined_logs = implode("<br><br>", $_SESSION['POprocess_log']);
							$combined_logs .= sprintf( __('<br><br>CSR-PO-%s is being processed by %s at %s.', CIP_TXTDOMAIN), $Order_ID,$current_user->user_email, date_i18n('d/m/Y H:i A') );
							create_cip_logs_entery($current_user->ID, 'Amplivo Profile Activity Log', '', 'sa', $combined_logs, true);
							unset($_SESSION['POprocess_log']);
							$out = array( "error" => 1, 'msg' => 'Failed to CSR-PO-".$Order_ID." status set to Paid and archived.', 'message' => $message );
							echo wp_json_encode( $out );
							exit;
						}
					}
				}
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
function findPurchaseOption($amount, $products) {
    $result = [];
    
    // Extract package prices and names for easy access
    $productPrices = array_column($products, 'packege_price');
    $productNames = array_column($products, 'packege_name');

    // Associate prices with their indexes to maintain relationship
    $productIndexMap = array_combine(array_keys($productPrices), $productPrices);

    // Sort product indexes by price in descending order for efficient selection
    arsort($productIndexMap);

    // Attempt to find the maximum total without exceeding the amount
    foreach ($products as $key => $item) {
		$price = $item['packege_price'];
		$productNames = $item['packege_name'];
        while ($amount >= $price) {
            $ProductID[] = $key;
            $result[] = $productNames;
            $resultPrices[] = $price;
            $amount -= $price;
        }
    }

    return [$ProductID, $result, $resultPrices];
}
function getpackages () {
	global $wpdb;
	$logTable = $wpdb->prefix . 'sa_packages';
	$results = $wpdb->get_results("SELECT packageid, heading, euro_amount FROM $logTable WHERE active = 1 ORDER BY `euro_amount` DESC", ARRAY_A);
	$output = [];
	foreach ($results as $row) {
		$key = intval($row['packageid']);
		$output[$key] = [
			'packege_name' => $row['heading'],
			'packege_price' => floatval($row['euro_amount'])
		];
	}
	return $output;
}
function splitAmount($amount, $maxChunk = 10000) {
    $chunks = [];
    while ($amount > 0) {
        if ($amount > $maxChunk) {
            $chunks[] = $maxChunk;
            $amount -= $maxChunk;
        } else {
            $chunks[] = $amount;
            $amount = 0;
        }
    }
    return $chunks;
}
//237 - export holders data legecy
add_action('wp_ajax_export_holders_data_legecy', 'export_holders_data_legecy');
function export_holders_data_legecy(){
	global $defaultColumnsArr;
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 ORDER BY `id` DESC");

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

	$filter_qry = "";
	$filterByConditions = json_decode( stripslashes( $_REQUEST['filterByCondition'] ), true );
	$filterBy = "";
	$filterByValue = "";
	if( !empty( $filterByConditions ) ){
		$filterBy = $filterByConditions['filter_condition_type'];
		$filterByValue = $filterByConditions['filter_condition_value'];
	}
	//237 - advance filter
	//Username
	$filterByConditionUsername = json_decode( stripslashes( $_REQUEST['filterByConditionUsername'] ), true );
	$filterByUsername = "";
	$filterByValueUsername = "";
	if( !empty( $filterByConditionsUsername ) ){
		$filterByUsername = $filterByConditionsUsername['filter_condition_type'];
		$filterByValueUsername = $filterByConditionsUsername['filter_condition_value'];
	}

	//email
	$filterByConditionEmail = json_decode( stripslashes( $_REQUEST['filterByConditionEmail'] ), true );
	$emailfilterBy = "";
	$emailfilterByValue = "";
	if( !empty( $filterByConditionEmail ) ){
		$emailfilterBy = $filterByConditionEmail['filter_condition_type'];
		$emailfilterByValue = $filterByConditionEmail['filter_condition_value'];
	}

	//Pool reference
	$filterByConditionPool_ref = json_decode( stripslashes( $_REQUEST['filterByConditionPool_ref'] ), true );
	$filterByPoolRef = "";
	$filterByValuePoolRef = "";
	if( !empty( $filterByConditionPool_ref ) ){
		$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type'];$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value'];
	}

	//Corp approved / Status
	$filterByConditionCorp_approved = json_decode( stripslashes( $_REQUEST['filterByConditionCorp_approved'] ), true );
	$filterByCorp_approved = "";
	$filterByValueCorp_approved = "";
	if( !empty( $filterByConditionCorp_approved ) ){
		$filterByCorp_approved = $filterByConditionCorp_approved['filter_condition_type'];$filterByValueCorp_approved = $filterByConditionCorp_approved['filter_condition_value'];
	}

	//Eth_address / wallet address
	$filterByConditionEth_address = json_decode( stripslashes( $_REQUEST['filterByConditionEth_address'] ), true );
	$eth_addressfilterBy = "";
	$eth_addressfilterByValue = "";
	if( !empty( $filterByConditionEth_address ) ){
		$eth_addressfilterBy = $filterByConditionEth_address['filter_condition_type'];
		$eth_addressfilterByValue = $filterByConditionEth_address['filter_condition_value'];
		if(!empty($filterByConditionEth_address['eth_address'])){
			$eth_address_isexcatly = $filterByConditionEth_address['eth_address'];
		}
	}

	//Reference
	$filterByConditionReference = json_decode( stripslashes( $_REQUEST['filterByConditionReference'] ), true );
	$referencefilterBy = "";
	$referencefilterByValue = "";
	$reference_isexcatly = "";
	if( !empty( $filterByConditionReference ) ){
		$referencefilterBy = $filterByConditionReference['filter_condition_type'];
		$referencefilterByValue = $filterByConditionReference['filter_condition_value'];
		if(!empty($filterByConditionReference['reference'])){
			$reference_isexcatly = $filterByConditionReference['reference'];
		}
	}

	//CSR Initial Amount
	$filterByConditionCsr_amount_initial = json_decode( stripslashes( $_REQUEST['filterByConditionCsr_amount_initial'] ), true );
	$csr_amount_initialfilterBy = "";
	$csr_amount_initialfilterByValue = "";
	if( !empty( $filterByConditionCsr_amount_initial ) ){
		$csr_amount_initialfilterBy = $filterByConditionCsr_amount_initial['filter_condition_type'];
		$csr_amount_initialfilterByValue = $filterByConditionCsr_amount_initial['filter_condition_value'];
	}

	//CSR Distributed
	$filterByConditionCsr_amount_issued = json_decode( stripslashes( $_REQUEST['filterByConditionCsr_amount_issued'] ), true );
	$csr_amount_issuedfilterBy = "";
	$csr_amount_issuedfilterByValue = "";
	if( !empty( $filterByConditionCsr_amount_issued ) ){
		$csr_amount_issuedfilterBy = $filterByConditionCsr_amount_issued['filter_condition_type'];
		$csr_amount_issuedfilterByValue = $filterByConditionCsr_amount_issued['filter_condition_value'];
	}

	//CSR Amount due
	$filterByConditionAmount_due = json_decode( stripslashes( $_REQUEST['filterByConditionAmount_due'] ), true );
	$amount_duefilterBy = "";
	$amount_duefilterByValue = "";
	if( !empty( $filterByConditionAmount_due ) ){
		$amount_duefilterBy = $filterByConditionAmount_due['filter_condition_type'];
		$amount_duefilterByValue = $filterByConditionAmount_due['filter_condition_value'];
	}

	//Notes/Comments
	$filterByConditionNotes_external = json_decode( stripslashes( $_REQUEST['filterByConditionNotes_external'] ), true );
	$notes_externalfilterBy = "";
	$notes_externalfilterByValue = "";
	if( !empty( $filterByConditionNotes_external ) ){
		$notes_externalfilterBy = $filterByConditionNotes_external['filter_condition_type'];
		$notes_externalfilterByValue = $filterByConditionNotes_external['filter_condition_value'];
	}

	//Corp Notes/Comments
	$filterByConditionNotes_internal = json_decode( stripslashes( $_REQUEST['filterByConditionNotes_internal'] ), true );
	$internalfilterBy = "";
	$internalfilterByValue = "";
	if( !empty( $filterByConditionNotes_internal ) ){
		$internalfilterBy = $filterByConditionNotes_internal['filter_condition_type'];
		$internalfilterByValue = $filterByConditionNotes_internal['filter_condition_value'];
	}
	// 237 - advance filter END

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	//237 - advance filter

	if( !empty($filterByConditionEmail['email']) ){
		$filters['email_filter'] = trim( $emailfilterByValue );
	}
	if( $amount_duefilterBy != 'none' && $amount_duefilterBy != '' ){
		$filters['amount_due_filter'] = trim( $amount_duefilterByValue );
	}
	if(!empty($filterByConditionUsername['username']) ){
		$filters['username_filter'] = trim( $filterByValueUsername );
	}
	if( !empty($filterByConditionPool_ref['pool_ref']) ){
		$filters['pool_ref_filter'] = $filterByValuePoolRef;
	}
	if(!empty($filterByConditionCorp_approved['corp_approved'])){
		$filters['corp_approved_filter'] = $filterByValueCorp_approved;
	}
	if( $referencefilterBy != 'none' && $referencefilterBy != '' ){
		$filters['reference_filter'] = trim( $referencefilterByValue );
	}
	if( $eth_addressfilterBy != 'none' && $eth_addressfilterBy != '' ){
		$filters['eth_address_filter'] = $eth_addressfilterByValue;
	}
	if( $csr_amount_initialfilterBy != 'none' && $csr_amount_initialfilterBy != '' ){
		$filters['csr_amount_initial_filter'] = $csr_amount_initialfilterByValue;
	}
	if( $csr_amount_issuedfilterBy != 'none' && $csr_amount_issuedfilterBy != '' ){
		$filters['csr_amount_issued_filter'] = trim( $csr_amount_issuedfilterByValue );
	}
	if( $notes_externalfilterBy != 'none' && $notes_externalfilterBy != '' ){
		$filters['notes_external_filter'] = trim( $notes_externalfilterByValue );
	}
	if( $internalfilterBy != 'none' && $internalfilterBy != '' ){
		$filters['notes_internal_filter'] = trim( $internalfilterByValue );
	}
	// 237 - advance filter END


	// if( $filterBy != 'none' ){
	// 	$filters['notes_external'] = trim( $filterByValue );
	// }

	// $filters['filterBy'] = $filterBy;
	// $filters['filterByValue'] = $filterByValue;

	$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'saved_amount');
	$isDateColumn = array('redemption_date', 'claim_date', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'saving_date', 'saving_start_date');

	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){

			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			// 237 advance filter - add reference, email, notes_internal, notes_external,eth_address
			}else if( $filterKey == 'username' || $filterKey == 'reference' || $filterKey == 'email' || $filterKey == 'eth_address' ){
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( $filterKey == 'notes_internal' || $filterKey == 'notes_external' ){
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( in_array( $filterKey, $isNumericColumn ) ){ //numeric filter
				if( str_contains($filterData, '-') ){ //between
					$filterDataMinMax = explode('-', $filterData);
					$filter_qry .= " AND `$filterKey` BETWEEN $filterDataMinMax[0] AND $filterDataMinMax[1]";
				}else if( str_contains($filterData, '>') || str_contains($filterData, '>=') || str_contains($filterData, '<') || str_contains($filterData, '<=') || str_contains($filterData, '!=') ){ //Greater than or equal to AND Less than or equal to
					$filter_qry .= " AND `$filterKey` $filterData";
				}else{
					$filter_qry .= " AND `$filterKey` = " . $filterData . "";
				}
			}else if( in_array( $filterKey, $isDateColumn ) ){ //date filter
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') BETWEEN STR_TO_DATE('$filterDataMinMax[0]','%d/%m/%Y') AND STR_TO_DATE('$filterDataMinMax[1]','%d/%m/%Y')";
				}else{
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d/%m/%Y') = STR_TO_DATE('$filterData','%d/%m/%Y')";
				}
			}else if( $filterKey == 'notes_external' ){
				if( $filterBy != 'none' ){
					if( $filterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $filterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $filterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $filterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " %'";
					}else if( $filterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '% " . $filterData . " |%'";
					}else if( $filterBy == 'is_exactly' ){
						$filter_qry .= " AND `$filterKey` LIKE '%| " . $filterData . " |%'";
					}
				}
			}else if( $filterKey == 'username_filter' ){
				if( !empty($filterByConditionUsername['username'])){
                    $filterKey = 'username';

					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionUsername['username']) . "')";

					//original querry
					//$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
				}
			}else if( $filterKey == 'reference_filter' ){
				if( $referencefilterBy != 'none' && $referencefilterBy != '' ){
					$filterKey = 'reference';
					if( $referencefilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $referencefilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $referencefilterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $referencefilterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $referencefilterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '" . $filterData . "%'";
					}else if( $referencefilterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "'";
					}else if( $referencefilterBy == 'is_exactly' ){
						//$filter_qry .= " AND `$filterKey` LIKE '%" . $reference_isexcatly . "%'";
						$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $reference_isexcatly) . "')";

					}
				}
			}else if( $filterKey == 'email_filter' ){
				$filterKey = 'email';
				if( !empty($filterByConditionEmail['email'])){
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionEmail['email']) . "')";
				}

			}else if( $filterKey == 'pool_ref_filter' ){
				$filterKey = 'pool_ref';
				if( !empty($filterByConditionPool_ref['pool_ref']) ){
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionPool_ref['pool_ref']) . "')";
				}
			}else if( $filterKey == 'corp_approved_filter' ){
				if( !empty($filterByConditionCorp_approved['corp_approved']) ){
                    $filterKey = 'corp_approved';
					//die('++ crop');
					//print_r($filterByConditionCorp_approved['corp_approved']);
					$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterByConditionCorp_approved['corp_approved']) . "')";

				}
			}else if( $filterKey == 'eth_address_filter' ){
				if( $eth_addressfilterBy != 'none' && $eth_addressfilterBy != ''){
					$filterKey == 'eth_address';
					if( $eth_addressfilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $eth_addressfilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $eth_addressfilterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $eth_addressfilterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $eth_addressfilterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '" . $filterData . "%'";
					}else if( $eth_addressfilterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "'";
					}else if( $eth_addressfilterBy == 'is_exactly' ){
						if( !empty($eth_address_isexcatly)){
							$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $eth_address_isexcatly) . "')";
						}
					}
				}
			}else if( $filterKey == 'csr_amount_initial_filter' ){
				$filterKey = 'csr_amount_initial';
				if( $csr_amount_initialfilterBy != 'none' && $csr_amount_initialfilterBy != ''){
					if( $csr_amount_initialfilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $csr_amount_initialfilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $csr_amount_initialfilterBy == 'greater_than' ){
						$filter_qry .= " AND `$filterKey` > '" . floatval($filterData) . "'";
					}else if( $csr_amount_initialfilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . floatval($filterData) . "'";
					}else if( $csr_amount_initialfilterBy == 'equal_to' ){
						$filter_qry .= " AND `$filterKey` = '" . floatval($filterData) . "'";
					}
				}
			}else if( $filterKey == 'csr_amount_issued_filter' ){
				$filterKey = 'csr_amount_issued';
				if( $csr_amount_issuedfilterBy != 'none' && $csr_amount_issuedfilterBy != ''){
					if( $csr_amount_issuedfilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $csr_amount_issuedfilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $csr_amount_issuedfilterBy == 'greater_than' ){
						$filter_qry .= " AND `$filterKey` > '" . floatval($filterData) . "'";
					}else if( $csr_amount_issuedfilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . floatval($filterData) . "'";
					}else if( $csr_amount_issuedfilterBy == 'equal_to' ){
						$filter_qry .= " AND `$filterKey` = '" . floatval($filterData) . "'";
					}
				}
			}else if( $filterKey == 'amount_due_filter' ){
				$filterKey = 'amount_due';
				if( $amount_duefilterBy != 'none' && $amount_duefilterBy != ''){
					if( $amount_duefilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $amount_duefilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $amount_duefilterBy == 'greater_than' ){

						$filter_qry .= " AND `$filterKey` > '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'equal_to' ){
						$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
					}
				}
			}else if( $filterKey == 'notes_external_filter' ){
				if( $notes_externalfilterBy != 'none' && $notes_externalfilterBy != ''){
					$filterKey = 'notes_external';

					if( $notes_externalfilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $notes_externalfilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $notes_externalfilterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $notes_externalfilterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $notes_externalfilterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '|" . $filterData . "%'";
					}else if( $notes_externalfilterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "|%'";
					}else if( $notes_externalfilterBy == 'is_exactly' ){
						$filter_qry .= " AND `$filterKey` LIKE '%|" . $filterData . "|%'";
					}
				}
			}else if( $filterKey == 'notes_internal_filter' ){

				if( $internalfilterBy != 'none' ){
					$filterKey = 'notes_internal';
					if( $internalfilterBy == 'is_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NULL OR `$filterKey` = '' )";
					}else if( $internalfilterBy == 'is_not_empty' ){
						$filter_qry .= " AND ( `$filterKey` IS NOT NULL AND `$filterKey` <> '' )";
					}else if( $internalfilterBy == 'contains_text' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}else if( $internalfilterBy == 'does_not_contains_text' ){
						$filter_qry .= " AND `$filterKey` NOT LIKE '%" . $filterData . "%'";
					}else if( $internalfilterBy == 'starts_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '" . $filterData . "%'";
					}else if( $internalfilterBy == 'ends_with' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "'";
					}else if( $internalfilterBy == 'is_exactly' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
					}
				}
				// 237 - advance filter END
			}else{

				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
	}
	$needColumns = array('reference', 'username', 'email', 'eth_address', 'pool_ref', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'corp_approved');
	$columnOrders = (array)get_option('cip_sm_column_order');
	$columnsLabelArr = (array)get_option('cip_sm_column_labels');
	$columnsArr = array();
	if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
		foreach( $columnOrders as $columnOrder ){
			if( in_array( $columnOrder, $needColumns ) ){
				$columnsArr[$columnOrder] = $defaultColumnsArr[$columnOrder];
			}
		}
	}
	if( empty( $columnsArr ) ){
		$columnsArr = $defaultColumnsArr;
	}
	global $wpdb;
	$sheetCounter = 0;
	
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}
	$getTHsData = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY $orderby $order");

	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'reference', 'eth_address', 'occurs_times', 'csr_amount_initial', 'csramount_by_ethaddress', 'csr_amount_issued', 'amount_due', 'username', 'csramount_byusername', 'occurs_times_user', 'first_name', 'last_name', 'redemption_date', 'claim_date', 'email', '_user_status', 'kyc_status', 'pool_ref', 'approvedkyc', 'corp_approved', 'notes_external', 'notes_internal', 'Position', 'text_1', 'text_2', 'text_3', 'text_4', 'text_5', 'text_6', 'text_7', 'text_8', 'text_9', 'text_10', 'date_1', 'date_2', 'date_3', 'date_4', 'date_5', 'date_6', 'date_7', 'date_8', 'date_9', 'date_10', 'int_1', 'int_2', 'int_3', 'int_4', 'int_5', 'int_6', 'int_7', 'int_8', 'int_9', 'int_10', 'note_1', 'note_2', 'note_3', 'note_4', 'note_5', 'note_6', 'note_7', 'note_8', 'note_9', 'note_10', 'imported_by', 'import_at', 'last_update_at', 'saved_amount', 'saving_date', 'saving_start_date', 'saving_interest', 'saving_periods', 'saving_state', 'sign_verify', 'transhash', 'contract_address', 'receiver_address', 'ma_enabled', 'token' );
	fputcsv($exportFile, $columnHeader);
	if( $getTHsData ){
		foreach( $getTHsData as $getTHData ){
			$redemption_date_formatted = "";
			if( $getTHData->redemption_date ){
				$formattedRDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->redemption_date );
				if( $formattedRDate ){
					$redemption_date_formatted = $formattedRDate->format('d/m/Y');
				}
			}
			$claim_date_formatted = "";
			if( $getTHData->claim_date ){
				$formattedCDate = DateTime::createFromFormat( 'd/m/Y', $getTHData->claim_date );
				if( $formattedCDate ){
					$claim_date_formatted = $formattedCDate->format('d/m/Y');
				}
			}
			$rowData = array( $getTHData->reference, $getTHData->eth_address, $getTHData->occurs_times, $getTHData->csr_amount_initial, $getTHData->csramount_by_ethaddress, $getTHData->csr_amount_issued, $getTHData->amount_due, $getTHData->username, $getTHData->csramount_byusername, $getTHData->occurs_times_user, $getTHData->first_name, $getTHData->last_name, $redemption_date_formatted, $claim_date_formatted, $getTHData->email, $getTHData->_user_status, $getTHData->kyc_status, $getTHData->pool_ref, $getTHData->approvedkyc, $getTHData->corp_approved, $getTHData->notes_external, $getTHData->notes_internal, $getTHData->position, $getTHData->text_1, $getTHData->text_2, $getTHData->text_3, $getTHData->text_4, $getTHData->text_5, $getTHData->text_6, $getTHData->text_7, $getTHData->text_8, $getTHData->text_9, $getTHData->text_10, $getTHData->date_1, $getTHData->date_2, $getTHData->date_3, $getTHData->date_4, $getTHData->date_5, $getTHData->date_6, $getTHData->date_7, $getTHData->date_8, $getTHData->date_9, $getTHData->date_10, $getTHData->int_1, $getTHData->int_2, $getTHData->int_3, $getTHData->int_4, $getTHData->int_5, $getTHData->int_6, $getTHData->int_7, $getTHData->int_8, $getTHData->int_9, $getTHData->int_10, $getTHData->note_1, $getTHData->note_2, $getTHData->note_3, $getTHData->note_4, $getTHData->note_5, $getTHData->note_6, $getTHData->note_7, $getTHData->note_8, $getTHData->note_9, $getTHData->note_10, $getTHData->imported_by, $getTHData->import_at, $getTHData->last_update_at, $getTHData->saved_amount, $getTHData->saving_date, $getTHData->saving_start_date, $getTHData->saving_interest, $getTHData->saving_periods, $getTHData->saving_state, $getTHData->sign_verify, $getTHData->transhash, $getTHData->contract_address, $getTHData->receiver_address, $getTHData->ma_enabled, $getTHData->token );
			fputcsv($exportFile, $rowData);
			$excelRow++;
		}
	}
	$current_user = wp_get_current_user();
	$logs = sprintf( __('Partial Export Holder Data by %s at %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A') );
	create_cip_logs_entery( $current_user->ID, 'sa', '','sa', $logs, true );
	fseek($exportFile, 0);
	$file_name = 'CSRHolder-'.date_i18n('d-m-Y H-i-s');
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}

add_filter('gform_next_button', 'input_to_button', 10, 2);
function input_to_button($button, $form) {
	if ($form['id'] !== 4) {
        return $button;
    }
    return sprintf( __('<a href="%s" type="button" class="gform_previous_button gform-theme-button gform-theme-button--secondary button back-to-per-page">Previous</a> %s', CIP_TXTDOMAIN), get_permalink(4258), $button );
}

add_action('wp_ajax_export_my_csr','export_my_csr');
function export_my_csr(){
	global $defaultColumnsArr;
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

		$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
		$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$filter_qry = "";

	$my_csr_table_date_filters = json_decode( stripslashes( $_REQUEST['my_csr_table_date_filter'] ), true );
	if( !empty( $my_csr_table_date_filters ) ){
		if( $my_csr_table_date_filters['fromdate'] != '' && $my_csr_table_date_filters['todate'] != '' ){
			$filter_qry .= "AND ( ( STR_TO_DATE(redemption_date,'%d/%m/%Y') >= STR_TO_DATE('" . $my_csr_table_date_filters['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(redemption_date,'%d/%m/%Y') <= STR_TO_DATE('" . $my_csr_table_date_filters['todate'] . "', '%d/%m/%Y') ) OR ( STR_TO_DATE(claim_date,'%d/%m/%Y') >= STR_TO_DATE('" . $my_csr_table_date_filters['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(claim_date,'%d/%m/%Y') <= STR_TO_DATE('" . $my_csr_table_date_filters['todate'] . "', '%d/%m/%Y') ) )";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 AND email = '".$refAccount."' $filter_qry ORDER BY `id` DESC");
	}

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'token' || $filterKey == 'corp_approved' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
	}
	$getTHsData = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 AND email = '".$refAccount."' $filter_qry ORDER BY $orderby $order");

	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 'token','reference','corp_approved','eth_address','csr_amount_initial', 'csr_amount_issued', 'amount_due','pool_ref', 'notes_external', 'text_10', 'date_1', 'saved_amount', 'saving_date', 'saving_start_date', 'saving_interest', 'saving_periods');
    fputcsv($exportFile, $columnHeader);
    if( $getTHsData ){
		foreach( $getTHsData as $getTHData ){

			$rowData = array( $getTHData->token, $getTHData->reference, $getTHData->corp_approved, $getTHData->eth_address, $getTHData->csr_amount_initial, $getTHData->csr_amount_issued, $getTHData->amount_due, $getTHData->pool_ref, $getTHData->notes_external, $getTHData->text_10, $getTHData->date_1, $getTHData->saved_amount, $getTHData->saving_date, $getTHData->saving_start_date, $getTHData->saving_interest, $getTHData->saving_periods );
			fputcsv($exportFile, $rowData);
			$excelRow++;
		}
	}
    $current_user = wp_get_current_user();
	
	fseek($exportFile, 0);
	$file_name = 'MyCSR-'.date_i18n('d-m-Y H-i-s');
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}
add_action('wp_ajax_export_paid_po_invoice_report','export_paid_po_invoice_report');
function export_paid_po_invoice_report(){
	global $wpdb;
    $wpdb_prefix = $wpdb->prefix;
    $invoice= $wpdb_prefix.'cip_member_invoice';
	// $ArchiveStatus = (isset( $_POST['ArchiveStatus'] ) && $_POST['ArchiveStatus'] == 'true') ? 'Yes' : 'No';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $invoice WHERE `Status` = 'Paid' AND `ArchiveStatus` = 'Yes' ORDER BY `ProformaInvoiceNumber` DESC");

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

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			$filterData = trim($filterData);
			if( $filterKey == 'Date' || $filterKey == 'PaidDate' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filterDataMinMax0 = DateTime::createFromFormat('d/m/Y', $filterDataMinMax[0]);
					$filterDataMinMax0Date = $filterDataMinMax0->format('Y-m-d');

					$filterDataMinMax1 = DateTime::createFromFormat('d/m/Y', $filterDataMinMax[1]);
					$filterDataMinMax1Date = $filterDataMinMax1->format('Y-m-d');
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";
				}else{
					$filterDataObj = DateTime::createFromFormat('d/m/Y', $filterData);
					$filterData = $filterDataObj->format('Y-m-d');
					$filter_qry .= " AND STR_TO_DATE(`$filterKey`,'%d-%m-%Y') = '$filterData'";
				}
			}else if($filterKey == 'token'){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $invoice WHERE `Status` = 'Paid' AND `ArchiveStatus` = 'Yes' $filter_qry");
	}

	if(isset( $_POST['limit'] )){
		$getinvoicetable = $wpdb->get_results("SELECT * FROM $invoice WHERE `Status` = 'Paid' AND `ArchiveStatus` = 'Yes' $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	}else{
		$getinvoicetable = $wpdb->get_results("SELECT * FROM $invoice WHERE `Status` = 'Paid' AND `ArchiveStatus` = 'Yes' $filter_qry ORDER BY `$orderby` $order");
	}

	$exportFile = fopen('php://memory', 'w');
	$columnHeader = array( 
		'id',
		'PO Number',
		'Date',
		'Invoice Number',
		'Paid Date',
		'Status',
		'Amplivo username',
		'First Name',
		'Last Name',
		'Email',
		'Sponsor ID',
		'Net Amount',
		'VAT Amount',
		'Gross Amount',
		'Vat Number',
		'Business Name',
		'Country',
		'Address1',
		'Address2',
		'City',
		'State',
		'Zipcode',
		'token'
	);
    fputcsv($exportFile, $columnHeader);
    if( $getinvoicetable ){
		foreach( $getinvoicetable as $getTHData ){

			$rowData = array( 
				$getTHData->id, 
				$getTHData->ProformaInvoiceNumber, 
				$getTHData->Date,
				$getTHData->InvoiceNumber,
				$getTHData->PaidDate,
				$getTHData->Status,
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->Username)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->FirstName)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->LastName)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->Email)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->IntroducedBy)),
				$getTHData->GrossAmount,
				$getTHData->VATAmount,
				$getTHData->NetAmount,
				$getTHData->VatNumber,
				// $getTHData->POVATAmount,
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->BusinessName)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->Country)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->Address1)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->Address2)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->City)),
				normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $getTHData->State)),
				$getTHData->Zipcode,
				$getTHData->token 
			);
			fputcsv($exportFile, $rowData);
			$excelRow++;
		}
	}
    $current_user = wp_get_current_user();
	
	fseek($exportFile, 0);
	$file_name = 'PO/Invoice Report-'.date_i18n('d-m-Y H-i-s');
	header('content-type:application/csv;charset=UTF-8');
	header('Content-Disposition: attachment; filename="'.$file_name.'.csv"');
	fpassthru($exportFile);
	fclose($exportFile);
	exit;
}
function normalizeText($text) {
    return ucwords(strtolower(trim($text)));
}
//include kyb files
include 'cip-helper-kyb.php';
include 'package/package.php';
include 'includes/user_wallet/user_wallet.php';
include 'includes/award_report/award_report.php';
include 'includes/mfp-settings/mfp-settings.php';
include 'includes/detect_site_mode/detect_site_mode.php';