<?php
add_action('wp_ajax_tokenholder_loader','cip_tokenholder_loader_cb');
function cip_tokenholder_loader_cb(){
	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'];
	}

	//coin
	$filterByConditionCoin = json_decode( stripslashes( $_REQUEST['filter_by_coin'] ), true );
	$filterByCoin = "";
	$filterByValueCoin = "";
	if( !empty( $filterByConditionCoin ) ){
		$filterByCoin = $filterByConditionCoin['filter_condition_type'];
		$filterByValueCoin = $filterByConditionCoin['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 );
	}
	if( $filterByCoin != 'none' && $filterByCoin != '' ){
		$filters['coin_filter'] = trim( $filterByValueCoin );
	}
	// 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 == 'greater_than_equal' ){
						$filter_qry .= " AND `$filterKey` >= '" . floatval($filterData) . "'";
					}else if( $csr_amount_initialfilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . floatval($filterData) . "'";
					}else if( $csr_amount_initialfilterBy == 'less_than_equal' ){
						$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 == 'greater_than_equal' ){
						$filter_qry .= " AND `$filterKey` >= '" . floatval($filterData) . "'";
					}else if( $csr_amount_issuedfilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . floatval($filterData) . "'";
					}else if( $csr_amount_issuedfilterBy == 'less_than_equal' ){
						$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 == 'greater_than_equal' ){
						$filter_qry .= " AND `$filterKey` >= '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than' ){
						$filter_qry .= " AND `$filterKey` < '" . $filterData . "'";
					}else if( $amount_duefilterBy == 'less_than_equal' ){
						$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 . "%'";
					}
				}
			}else if( $filterKey == 'coin_filter' ){
				if( $filterByCoin != 'none' ){
					$filterKey = 'coin';
					if( $filterByCoin == 'csr' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}else if( $filterByCoin == 'csr25' ){
						$filter_qry .= " AND `$filterKey` LIKE '%" . $filterByCoin . "%'";
					}
				}
				// 237 - advance filter END
			}else{

				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}

		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $filter_qry ORDER BY `id` DESC");
	}

	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$saUserData = get_user_by( 'id', $user_id );
	global $defaultColumnsArr;
	if( $saUserData && in_array( "supportagent", $saUserData->roles ) ){
		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsSAColumnOption = (array)get_option('cip_column_sa_toggle_columns');
		$columnsSAToggleArr = (array)get_user_meta( $user_id, 'cip_sagent_toggle_columns', true );
		$columnsArr = array();
		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
			foreach( $columnOrders as $columnOrder ){
				if( isset( $columnsSAToggleArr[$columnOrder] ) ){
					$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
				}
			}
			if( empty( $columnsArr ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsSAColumnOption[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}else{
			unset( $defaultColumnsArr['imported_by'] );
			unset( $defaultColumnsArr['import_at'] );
			unset( $defaultColumnsArr['last_update_at'] );
			$columnsArr = $defaultColumnsArr;
		}
	}else{
		unset( $defaultColumnsArr['imported_by'] );
		unset( $defaultColumnsArr['import_at'] );
		unset( $defaultColumnsArr['last_update_at'] );
		$columnsArr = $defaultColumnsArr;
	}
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			if( $isSelectAll == 1 ){
				$currentSelected = 1;
			}else if( $isSelectAll == 0 ){
				$currentSelected = 0;
			}
			$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_SASELECTION_PIC'));
			// $decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			//$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);

			$sessionSaCsrSelectionData = ( isset( $_SESSION['sessionSaCsrSelectionData'] ) && !empty( $_SESSION['sessionSaCsrSelectionData'] ) ) ? $_SESSION['sessionSaCsrSelectionData'] : array();
			if( $isSelectAll == 1 && in_array( $rowEncryptId, $sessionSaCsrSelectionData ) ){
				$currentSelected = 0;
			}else if( $isSelectAll == 0 && !in_array( $rowEncryptId, $sessionSaCsrSelectionData ) ){
				$currentSelected = 1;
			}
			$row['rowiddata'] = '<input type="checkbox" name="rowiddata" class="rowiddata" value="'.$rowEncryptId.'" '.checked( $isSelectAll, $currentSelected, false ).' />';
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
						$columnsDataVal = cip_trim_notes( $columnsDataVal );
						$columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '<a href="javascript:void(0);" class="modelpop_notes" data-toggle="modal" data-target="#viewMoreModal" data-id="'.$getCurrentMember->id.'" data-viewmore="'.wpautop( $columnsDataVal ).'" data-toggle-tt1="tooltip" data-placement1="top" title="'.$columnsDataVal150.'" ><img src="'.CIP_PLUGIN_FOLDER.'/images/view-more.png" class="view-more-notes" /></a>' );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}
					if( $columnKey == 'position' ){
						$positionVal = '—';
						$positionText = __('Distribution Position not set... Try back later',CIP_TXTDOMAIN);
						if( $columnsDataVal ){
							$positionVal = $columnsDataVal;
							$positionText = sprintf( __('Distribution Position is set... congratulations you are at position %s in the distribution list',CIP_TXTDOMAIN), $columnsDataVal );
						}
						$columnsDataVal = '<a href="javascript:void(0);" data-id="'.$getCurrentMember->id.'" data-toggle-tt="tooltip" data-placement="top" title="'.$positionText.'" >'.$positionVal.'</a>';
					}
					if( in_array( $columnKey, $isNumericColumn ) && is_numeric( $columnsDataVal ) ){
						$columnsDataVal = number_format( $columnsDataVal );
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$editLink = add_query_arg( array(
				'action' => 'edit',
				'id' => $getCurrentMember->id,
			), get_the_permalink( $_REQUEST['pageid'] ) );
			$unVerifyLink = "";
			if( $verified ){
				$unVerifyLink = '<a href="javascript:void(0);" class="unverify_cth ml-2" data-toggle-tt="tooltip" data-placement="top" title="Unverify" data-eth="'.$getCurrentMember->id.'"><i class="fas fa-undo"></i></a>';
			}

			$row['action'] = '<a href="'.$editLink.'" title="edit"><i class="fas fa-edit"></i></a>'.$unVerifyLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		// 'test_query' => "SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset",
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_get_holder_options_data_select2_options', 'get_holder_options_data_select2_options');
function get_holder_options_data_select2_options() {
    global $wpdb;
    $table = $wpdb->prefix.'token_holder';     // Table name
    $column = sanitize_text_field($_GET['column']);    // Column name
    $search = sanitize_text_field($_GET['search']);    // Search value

    // Validate inputs
    if (empty($table) || empty($column) || empty($search)) {
        wp_send_json_error(['message' => 'Invalid parameters.'], 400);
    }

    // Build the SQL query dynamically (sanitize table and column names)
    $table = esc_sql($table);
    $column = esc_sql($column);
    $like = $wpdb->esc_like($search) . '%';

    // Execute query to fetch results
    $results = $wpdb->get_col($wpdb->prepare(
        "SELECT DISTINCT `$column` FROM `$table` WHERE `$column` LIKE %s LIMIT 100",
        $like
    ));

    // Send results back to the frontend
    if (!empty($results)) {
        wp_send_json_success($results);
    } else {
        wp_send_json_error(['message' => 'No results found.'], 404);
    }
}
add_action('wp_ajax_tokenholder_address_loader','cip_tokenholder_address_loader_cb');
function cip_tokenholder_address_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();
	$user_id = -1;

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE imported_by != ".$user_id." 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';

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE imported_by != ".$user_id." $filter_qry ORDER BY `id` DESC");
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE imported_by != ".$user_id." $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$user_id = get_current_user_id();
	$saUserData = get_user_by( 'id', $user_id );
	global $defaultColumnsArr;
	if( $saUserData && in_array( "supportagent", $saUserData->roles ) ){
		$columnsArr['email'] = __('Email',CIP_TXTDOMAIN);
		$columnsArr['eth_address'] = __('CSR Wallet Address',CIP_TXTDOMAIN);
		$columnsArr['eth_address_status'] = __('CSR address status',CIP_TXTDOMAIN);
	}
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			if( $columnsArr ){
				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 = '—';
							}
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_head','bst_filter_var_declarations');
function bst_filter_var_declarations(){
    if( is_user_logged_in() ){
    	global $wpdb;
    	$tableName = $wpdb->prefix.'token_holder';
    	$user_id = get_current_user_id();
    	$is_admin_can = false;
    	if( current_user_can('administrator') ){
    		$is_admin_can = true;
    	}
    	$user_id = -1;
    	$isDateFilter = false;
    	if( (isset( $_REQUEST['fromdate'] ) && isset( $_REQUEST['todate'] )) && (!empty( $_REQUEST['fromdate'] ) && !empty( $_REQUEST['todate'] )) ){
    		$isDateFilter = true;
    	}
		$CorpApprovedArr = array();
		if( is_page( 5699 ) || is_page( 9099 ) || is_page( 1307 ) || is_page( 6301 ) || is_page( 7233 ) ){
			if( $isDateFilter ){
				$getCorpApproved = $wpdb->get_results("SELECT DISTINCT `corp_approved` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL) AND ( ( STR_TO_DATE(redemption_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(redemption_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) OR ( STR_TO_DATE(claim_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(claim_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) ) ");
			}else{
				$getCorpApproved = $wpdb->get_results("SELECT DISTINCT `corp_approved` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL)");
			}
			if( $getCorpApproved ){
				foreach( $getCorpApproved as $corpApprovedVal ){
					$CorpApprovedArr[$corpApprovedVal->corp_approved] = $corpApprovedVal->corp_approved;
				}
			}
		}
		$CorpApprovedJson = json_encode( $CorpApprovedArr );

    	////////////////////////
		$userStatusArr = array();
		if( is_page( 5699 ) || is_page( 9099 ) || is_page( 1307 ) || is_page( 6301 ) || is_page( 7233 ) ){
			/* if( $isDateFilter ){
				$getUserStatus = $wpdb->get_results("SELECT DISTINCT `_user_status` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL) AND ( ( STR_TO_DATE(redemption_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(redemption_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) OR ( STR_TO_DATE(claim_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(claim_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) ) ");
			}else{
				$getUserStatus = $wpdb->get_results("SELECT DISTINCT `_user_status` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL)");
			}
			if( $getUserStatus ){
				foreach( $getUserStatus as $userStatusVal ){
					$userStatusArr[$userStatusVal->_user_status] = $userStatusVal->_user_status;
				}
			} */
			$userStatusArr = array(
				'abandoned' =>	'Abandoned',
				'active'	=>	'Active',
				'deleted'	=>	'Deleted',
				'lockout'	=>	'Lockout',
				'suspended'	=>	'Suspended',
				'external'	=>	'External',
			);
		}
    	$UserStatusJson = json_encode( $userStatusArr );

    	////////////////////////
		$kycStatusArr = array();
		if( is_page( 5699 ) || is_page( 9099 ) || is_page( 1307 ) || is_page( 6301 ) || is_page( 7233 ) ){
			/* if( $isDateFilter ){
				$getKycStatus = $wpdb->get_results("SELECT DISTINCT `kyc_status` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL) AND ( ( STR_TO_DATE(redemption_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(redemption_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) OR ( STR_TO_DATE(claim_date,'%d/%m/%Y') >= STR_TO_DATE('" . $_REQUEST['fromdate'] . "', '%d/%m/%Y') AND STR_TO_DATE(claim_date,'%d/%m/%Y') <= STR_TO_DATE('" . $_REQUEST['todate'] . "', '%d/%m/%Y') ) ) ");
			}else{
				$getKycStatus = $wpdb->get_results("SELECT DISTINCT `kyc_status` FROM `$tableName` WHERE (imported_by != ".$user_id." OR imported_by IS NULL)");
			}
			if( $getKycStatus ){
				foreach( $getKycStatus as $kycStatusVal ){
					$kycStatusArr[$kycStatusVal->kyc_status] = $kycStatusVal->kyc_status;
				}
			} */
			$kycStatusArr = array(
				'yes'	=>	'Yes',
				'no'	=>	'No'
			);
		}
		$KycStatusJson = json_encode( $kycStatusArr );

    	$logTable = $wpdb->prefix.'cip_logs';
    	$logTypeArr = array();
		
		if( is_page( 2051 ) ){
			$getLogTypes = $wpdb->get_results("SELECT DISTINCT `user_type` FROM `$logTable` WHERE 1 AND log_type != 'api_track'");
			if( $getLogTypes ){
				foreach( $getLogTypes as $getLogType ){
					$userTypeLabel = '—';
					if( $getLogType->user_type  == 'sm' ){
						$userTypeLabel = __('Support Manager',CIP_TXTDOMAIN);
					}else if( $getLogType->user_type  == 'sa' ){
						$userTypeLabel = __('Support Agent',CIP_TXTDOMAIN);
					}else if( $getLogType->user_type  == 'member' ){
						$userTypeLabel = __('Member',CIP_TXTDOMAIN);
					}else if( $getLogType->user_type  == 'MAs' ){
						$userTypeLabel = __('Member Assitant',CIP_TXTDOMAIN);
					}else if( $getLogType->user_type  == 'buyer' ){
						$userTypeLabel = __('Buyer',CIP_TXTDOMAIN);
					}
					$logTypeArr[ $getLogType->user_type ] = $userTypeLabel;
				}
			}
		}
		
    	$filterKycKybStatus = array(
    		'pending' 	=>	'Pending',
    		'reject'	=>	'Rejected',
    		'dropped'	=>	'Dropped',
    		'approved'	=>	'Approved',
    	);
    	
    	$AddressVerifyArr = [1 => 'Verified', 0 => 'Not verified'];
    	$AddressVerifyJson = json_encode( $AddressVerifyArr );
    	$filterVisibilityArr = [ 1 => __("Private", CIP_TXTDOMAIN), 2 => __("Restricted", CIP_TXTDOMAIN), 3 => __("Public", CIP_TXTDOMAIN) ];
    	$filterVisibilityjson = json_encode( $filterVisibilityArr );
    	$userStarRankJson = json_encode( [0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7] );
    	$withdrawalProcessStatusJson = json_encode( ['Pending' => __('Pending', CIP_TXTDOMAIN), 'Under review' => __('Under review', CIP_TXTDOMAIN)] );
    	$withdrawalProcessTokenJson = json_encode( ['csr' => __('CSR', CIP_TXTDOMAIN), 'csr25' => __('CSR25', CIP_TXTDOMAIN)] );
    
    	/**
    	 * CSR Pool Report distribution status filter drop down
    	 */
    	$DistributionStatusArr = array();
		if(is_page(8574)){
			$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';
			$getDistributionStatus = $wpdb->get_results("SELECT DISTINCT `distribution_status` FROM `$tableCsrPoolReports` WHERE 1");
			if( $getDistributionStatus ){
				foreach( $getDistributionStatus as $getDistributionStatusVal ){
					$DistributionStatusArr[$getDistributionStatusVal->distribution_status] = $getDistributionStatusVal->distribution_status;
				}
			}
		}
    	$distributionStatusJson = json_encode( $DistributionStatusArr );
    
    	/**
    	 * My CSR get  user status filter dropdown query
    	 */
    	$tableNameUser = $wpdb->prefix.'token_holder';
    	$refAccountUser = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
    	$userStatusQery = $wpdb->prepare(
    		"SELECT DISTINCT corp_approved
    		 FROM $tableNameUser
    		 WHERE email = %s AND corp_approved IS NOT NULL",
    		$refAccountUser
    	);
    	$statuses = $wpdb->get_col($userStatusQery);
    	$corpApprovedByUserArray = [];
    	foreach ($statuses as $status) {
    		$corpApprovedByUserArray[$status] = $status;
    	}
    
    	$corpApprovedByUserJson = json_encode($corpApprovedByUserArray);
    
    ?><script>var filterUserStatus = <?php echo $UserStatusJson; ?>; var filterKycStatus = <?php echo $KycStatusJson; ?>; var filterCorpApproved = <?php echo $CorpApprovedJson; ?>; var AddressVerifyStatus = <?php echo $AddressVerifyJson; ?>; var filterVisibilityStatus = <?php echo $filterVisibilityjson; ?>;var filterLogType = <?php echo json_encode( $logTypeArr ); ?>;var filterKycKybStatus = <?php echo json_encode( $filterKycKybStatus ); ?>;var userStarRank = <?php echo $userStarRankJson; ?>;var distributionStatus = <?php echo $distributionStatusJson; ?>;var withdrawalProcessStatus = <?php echo $withdrawalProcessStatusJson; ?>;var withdrawalProcessToken = <?php echo $withdrawalProcessTokenJson; ?>;var corpApprovedByUser = <?php echo $corpApprovedByUserJson; ?>;</script><?php
    }
}
add_action('wp_footer','cip_init_bs_paging_ajax_table_script');
function cip_init_bs_paging_ajax_table_script(){
	$pagingUrlData = array();
	$pagingUrlData['action'] = 'tokenholder_loader';
	$pagingUrlData['pageid'] = get_the_ID();
	$isBulkUser = 0;
	if( (isset( $_GET['fromdate'] ) && isset( $_GET['todate'] )) && (!empty( $_GET['fromdate'] ) && !empty( $_GET['todate'] )) ){
		$pagingUrlData['fromdate'] = $_GET['fromdate'];
		$pagingUrlData['todate'] = $_GET['todate'];
	}else if( ( isset( $_GET['action'] ) && $_GET['action'] == 'advanced_filter' ) && !empty( $_GET['usernames'] ) ){
		$pagingUrlData['usernames'] = $_GET['usernames'];
		$pagingUrlData['filteraction'] = $_GET['action'];
	}else if( ( isset( $_REQUEST['filteraction'] ) && $_REQUEST['filteraction'] == 'advanced_bulk_filter' ) && !empty( $_REQUEST['bulk_usernames'] ) ){
		$bulk_usernames = explode(PHP_EOL, trim($_REQUEST['bulk_usernames']));
		// $usernames = json_encode( $bulk_usernames );
		// $pagingUrlData['usernames'] = $usernames;
		$pagingUrlData['filteraction'] = $_REQUEST['filteraction'];
		$pagingUrlData['isBulkUser'] = 1;
		$isBulkUser = 1;
	}
	$data_url = add_query_arg( $pagingUrlData, admin_url( 'admin-ajax.php' ) );
	$AddreessListUrlData = array();
	$AddreessListUrlData['action'] = 'tokenholder_address_loader';
	$AddreessListUrlData['pageid'] = get_the_ID();
	$address_list_data_url = add_query_arg( $AddreessListUrlData, admin_url( 'admin-ajax.php' ) );
	$ma_csrlist_data_url = add_query_arg( [
			'action'	=>	'ma_tokenholder_loader',
			'pageid'	=>	get_the_ID(),
		], admin_url( 'admin-ajax.php' ) );
	$distribution_url = add_query_arg( [
			'action'	=>	'tokenholder_distribution_loader',
			'pageid'	=>	get_the_ID(),
		], admin_url( 'admin-ajax.php' ) );

	$distribution_10_url = add_query_arg( [
			'action'	=>	'tokenholder_distribution_10_loader',
			'pageid'	=>	get_the_ID(),
		], admin_url( 'admin-ajax.php' ) );
	$sa_retirement_url = add_query_arg( [
		'action'	=>	'tokenholder_sa_retirement_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$sa_pending_review_url = add_query_arg( [
		'action'	=>	'sa_pending_review_logourl_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$distribution_weekly_table_url = add_query_arg( [
		'action'	=>	'distribution_weekly_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	//4966
	$csr_address_pending_review_url = add_query_arg( [
		'action'	=>	'csr_address_pending_review_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$csr_lsh_pending_review_url = add_query_arg( [
		'action'	=>	'csr_lsh_pending_review_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	//5690
	$csr_kyc_pending_review_url = add_query_arg( [
		'action'	=>	'csr_kyc_pending_review_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	// KYC/KYB
	$csr_kyb_pending_review_url = add_query_arg( [
		'action'	=>	'csr_kyb_pending_review_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	//5753
	$csr_withdraw_requests_url = add_query_arg( [
		'action'	=>	'csr_withdraw_requests_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$tokenholder_wallet_delivery_url = add_query_arg( [
		'action'	=>	'tokenholder_wallet_delivery_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$tokenholder_wallet_delivery_report_url = add_query_arg( [
		'action'	=>	'tokenholder_wallet_delivery_report_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$tokenholder_csr_transaction_history_deposit_url = add_query_arg( [
		'action'	=>	'csr_transaction_history_deposit_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$tokenholder_csr_transaction_history_withdrawals_url = add_query_arg( [
		'action'	=>	'csr_transaction_history_withdrawals_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_supportagent_users_list_url = add_query_arg( [
		'action'	=>	'cip_supportagent_users_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_completed_withdrawals_list_url = add_query_arg( [
		'action'	=>	'cip_completed_withdrawals_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_completed_withdrawals_all_list_url = add_query_arg( [
		'action'	=>	'cip_completed_withdrawals_all_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_simple_notes_management_list_url = add_query_arg( [
		'action'	=>	'cip_simple_notes_management_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_sms_alert_management_list_url = add_query_arg( [
		'action'	=>	'cip_sms_alert_management_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$cip_amount_wallet_table_url = add_query_arg( [
		'action'	=>	'cip_amount_wallet_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	$countries_management_table_url = add_query_arg( [
		'action'	=>	'countries_management_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/**
	 * Withdrawal block address listing ajax url
	 */
	$cip_withdrawal_block_address_list_table_url = add_query_arg( [
		'action'	=>	'cip_withdrawal_block_address_list_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/**
	 * Corporate user listing ajax url create
	 */
	$corporate_users_list_url = add_query_arg( [
		'action'	=>	'corporate_users_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/**
	 * Corporate users withdrawals listing ajax url create
	 */
	$corporate_user_request_withdrawal_list_url = add_query_arg( [
		'action'	=>	'corporate_user_request_withdrawal_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/**
	 * CSR pool report ajax url create
	 */
	$csr_pool_report_list_table_url = add_query_arg( [
		'action'	=>	'csr_pool_report_list_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/* CSR partial filtered */

	$partial_filtered_table_url = add_query_arg( [
		'action'	=>	'partial_filtered_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

	// header notice action
	$cip_notice_header_setting_url = add_query_arg( [
		'action'	=>	'cip_notice_header_setting_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	// header notice action
	/**
	 * My CSR Token holder table ajax url create
	 */
	$my_csr_token_holder_table_url = add_query_arg( [
		'action'	=>	'my_csr_token_holder_table_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
	/**
	 * My CSR Retirements table ajax url create
	 */
	$mycsr_table_retirment_url = add_query_arg( [
		'action'	=>	'mycsr_table_retirment_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );

?><script>
  jQuery(document).ready(function($){
	var partial_filtered_table_url = "<?php echo $partial_filtered_table_url ?>";
	if( $('#partial_filtered_table_responce').length > 0 ){
		var $tableThMa = $('#partial_filtered_table_responce');
		$tableThMa.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: partial_filtered_table_url,
			queryParams: function (p) {
				partial_export_filter = convertFormToJSON( '#partial_export_filter' );
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					'partial_export_filter': partial_export_filter,
				};
			},
			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();
				}
		  	}
		});
	}
	var my_csr_token_holder_table_url = "<?php echo $my_csr_token_holder_table_url ?>";
	if( $('#my_csr_token_holder_table').length > 0 ){
		var $tableThMa = $('#my_csr_token_holder_table');
		$(document).on('submit','#my_csr_table_date_filter',function(e){
			e.preventDefault();
			$('#my_csr_token_holder_table').bootstrapTable('refresh');
		});
		
		$(document).on('click','#my_csr_table_date_filter .filter_area_clear',function(e){
			$('#my_csr_table_date_filter [name="fromdate"],#my_csr_table_date_filter [name="todate"]').val('');
			$('#my_csr_token_holder_table').bootstrapTable('refresh');
		});
		$tableThMa.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: my_csr_token_holder_table_url,
			queryParams: function (p) {
				my_csr_table_date_filter = convertFormToJSON( '#my_csr_table_date_filter' );
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					'my_csr_table_date_filter': my_csr_table_date_filter
				};
			},
			rowAttributes: function(row, index) {
				return {
					'data-eth': row.ethid,
					'data-token': row.tokenEncrypt,
					'data-tokenType': row.tokenType,
				};
			},
			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();
				}
		  	}
		});
	}
	var mycsr_table_retirment_url = "<?php echo $mycsr_table_retirment_url ?>";
	if( $('#tokenholder_table_retirment_loader').length > 0 ){
		var $tableRetirementLoader = $('#tokenholder_table_retirment_loader');
		$tableRetirementLoader.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: mycsr_table_retirment_url,
			pagination: false,
			showFooter: false,
			queryParams: function (p) {
				return {};
			},
			rowAttributes: function(row, index) {
				return {
					'data-token': row.token,
					'data-eth': row.eth,
					'data-tokenType': row.tokenType,
				};
			},
			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();
				}
		  	}
		});
	}
	var data_url = "<?php echo $data_url ?>";
	if( $('#tokenholder_table_sa').length > 0){
		//$('#tokenholder_table_sa').addClass('initialized');
        var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

		var $tableThSa = $('#tokenholder_table_sa');
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		var isBulkUser = <?php echo $isBulkUser; ?>;
		stickyHeaderOffset = wpadminbar;
		var params = {};
		var filterByCondition = {};
		var thisRows = [];
		var isSelectAll = 0;

		var filterByConditionUsername = {};
		var filterByConditionEmail = {};
		var filterByConditionPool_ref = {};
		var filterByConditionCorp_approved = {};
		var filterByConditionReference = {};
		var filterByConditionEth_address = {};
		var filterByConditionCsr_amount_initial = {};
		var filterByConditionCsr_amount_issued = {};
		var filterByConditionAmount_due = {};
		var filterByConditionNotes_external = {};
		var filterByConditionNotes_internal = {};
		var filterByConditionCoin = {};
		var thisRows = [];




		// console.log(filterByConditionReference + 'data')
			let currentAjaxRequest = null;
            $tableThSa.bootstrapTable({
                method: 'post',
                contentType: 'application/x-www-form-urlencoded',
                url: data_url,
                searchTimeOut:1000,
                // dataType: "json",
                // data: data,
                queryParams: function (p) {

					if (currentAjaxRequest) {
						currentAjaxRequest.abort();
						$.unblockUI();
					}

					var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
					$.blockUI(block_config);
                    params = p.filter;
                    if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
                        isSelectAll = 1;
                    }else{
                        isSelectAll = 0;
                    }
                    filterByCondition = convertFormToJSON( '#filter_by_notes' );

                    filterByConditionParsed = JSON.parse( filterByCondition );
                    if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
                        $('.clear_all_csr_holder').hide();
                    }
                    filterByConditionUsername = convertFormToJSON( '#filter_by_username' );
                    filterByConditionEmail = convertFormToJSON( '#filter_by_email' );
                    filterByConditionPool_ref = convertFormToJSON( '#filter_by_pool_ref' );
                    filterByConditionCorp_approved = convertFormToJSON( '#filter_by_corp_approved' );
                    filterByConditionReference = convertFormToJSON( '#filter_by_reference' );
                    filterByConditionEth_address = convertFormToJSON( '#filter_by_eth_address' );
                    filterByConditionCsr_amount_initial = convertFormToJSON( '#filter_by_csr_amount_initial' );
                    filterByConditionCsr_amount_issued = convertFormToJSON( '#filter_by_csr_amount_issued' );
                    filterByConditionAmount_due = convertFormToJSON( '#filter_by_amount_due' );
                    filterByConditionNotes_external = convertFormToJSON( '#filter_by_notes_external' );
                    filterByConditionNotes_internal = convertFormToJSON( '#filter_by_notes_internal' );
                    filterByConditionCoin = convertFormToJSON( '#filter_by_coin' );
                    return {
                        columnfilter: p.filter,
                        limit: p.limit,
                        offset: p.offset,
                        sort: p.sort,
                        order: p.order,
                        isSelectAll: isSelectAll,
                        'filterByCondition': filterByCondition,

                        'filterByConditionUsername': filterByConditionUsername,
                        'filterByConditionEmail': filterByConditionEmail,
                        'filterByConditionPool_ref': filterByConditionPool_ref,
                        'filterByConditionCorp_approved': filterByConditionCorp_approved,
                        'filterByConditionReference': filterByConditionReference,
                        'filterByConditionEth_address': filterByConditionEth_address,
                        'filterByConditionCsr_amount_initial': filterByConditionCsr_amount_initial,
                        'filterByConditionCsr_amount_issued': filterByConditionCsr_amount_issued,
                        'filterByConditionAmount_due': filterByConditionAmount_due,
                        'filterByConditionNotes_external': filterByConditionNotes_external,
                        'filterByConditionNotes_internal': filterByConditionNotes_internal,
                        'filter_by_coin': filterByConditionCoin
                    };
                    // console.dir( p );
                    /* if( isBulkUser == 1 ){
                        // var data = new FormData( $('#bulk_filter_frm')[0] );
                        // var data = $('#bulk_filter_frm textarea[name="bulk_usernames"]').val();
                        return {
                            columnfilter: p.filter,
                            limit: p.limit,
                            offset: p.offset,
                            sort: p.sort,
                            order: p.order,
                            // bulk_usernames : data,
                        };
                    }else{
                        return {
                            columnfilter: p.filter,
                            limit: p.limit,
                            offset: p.offset,
                            sort: p.sort,
                            order: p.order,
                        };
                    } */
                },
                stickyHeader: true,
                // stickyHeaderOffsetY: stickyHeaderOffset,
                onPostBody: function (response){
                    $.unblockUI();
					currentAjaxRequest = null; // Clear the tracker
                    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();
                    }
                    $('.sticky-header .filter-control input.search-input').prop('readonly',false);
                    $('.filter-control select.form-control').removeClass('pointerEno');
                },
				ajaxOptions: {
					beforeSend: function (xhr) {
						currentAjaxRequest = xhr;
					},
					complete: function () {
						currentAjaxRequest = null;
					},
				},
                onSearch: function( search ){
                    $('.sticky-header .filter-control input.search-input').prop('readonly',true);
                    $('.filter-control select.form-control').addClass('pointerEno');
                    filterByConditionParsed = JSON.parse( filterByCondition );
                    if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
                        $('.clear_all_csr_holder').hide();
                    }else{
                        $('.clear_all_csr_holder').show();
                    }
                }
            });
		//store toggle column
		let lsname = '-hideColumn-tokenholder_table_sa'
		let hideColumn = JSON.parse(localStorage.getItem(lsname)) || [];
		let th = $tableThSa.find('thead tr th');
		th.each(function (index) {
			let attrTitle = $(this).attr('data-field')
			if (hideColumn.includes(attrTitle)) {
				$tableThSa.bootstrapTable('hideColumn', attrTitle);
			}
		})
		$tableThSa.on("column-switch.bs.table", function (e, field, checked) {
			if (checked && hideColumn.includes(field)) {
				// remove form local storage
				const index = hideColumn.indexOf(field);
				if (index > -1) {
					hideColumn.splice(index, 1);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			} else if (!checked) {
				if (hideColumn.includes(field)) {} else {
					hideColumn.push(field);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			}
		});
		$("body").on("change", ".toggle-all", function () {
			let $this = $(this);
			let div = $this.parent().parent()[0];
			$(div).find("input[type=checkbox]").each(function (index) {
				let checked = $(this).is(":checked");
				let field = $(this).attr("data-field");
				if (checked && hideColumn.includes(field)) {
					// remove form local storage
					const index = hideColumn.indexOf(field);
					if (index > -1) {
						hideColumn.splice(index, 1);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				} else if (!checked) {
					if (hideColumn.includes(field)) {
						// hands up nothing needed
					} else {
						// add in LS for nexttime
						hideColumn.push(field);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				}
			});
		});
		//store toggle column
		$('#toolbar').find('select').change(function () {
		});
		//237 advance filter
		// $('select[name="filter_condition_type"]').on('change', function(){
		// 	var condition_type = $(this).val();
		// 	var $filter_condition_value = $('input[name="filter_condition_value"]');
		// 	if( condition_type == 'none' || condition_type == 'is_empty' || condition_type == 'is_not_empty' ){
		// 		$filter_condition_value.hide();
		// 		$filter_condition_value.val('');
		// 	}else{
		// 		$filter_condition_value.show();
		// 	}
		// });
		$('body').on('change', 'input[name="toggleWDAll"]', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#tokenholder_table_sa thead th .filter-control .search-input:first').trigger(eve);
			$('.edit_csr_holder').show();
		});
		$('body').on('click', 'button.edit_csr_holder', function(){
			var isSelectAll = 0;
			if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'editCheckingCsrProcess', 'thisParams' : params, 'isSelectAll' : isSelectAll, 'filterByCondition': filterByCondition, '_micro' : "<?php echo wp_create_nonce('_XyEditCheckingProcessCsryX_'); ?>" };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#csrEditProcessModal .csrEditProcessBody').html('');
					$('#csrEditProcessModal').modal({backdrop: 'static',keyboard: false});
					// $('#csrEditProcessModal').modal('show');
					$('#csrEditProcessModal .csrEditProcessBody').html( obj.html );
					if( $('body').find('.csrEditProcessBody [data-toggle="tooltip"]').length > 0 ){
						$('body').find('.csrEditProcessBody [data-toggle="tooltip"]').tooltip();
					}
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$.unblockUI();
			});
			return false;
		});
		$('body').on('submit', '#csr_edit_notes_frm', function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1059, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
			$form = $(this);
			var isSelectAll = 0;
			if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var data = $(this).serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition;
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					$("#csrEditProcessModal").modal('hide');
					$.blockUI( block_config );
					window.location.reload();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});
		$('body').on('submit', '#editNoteElementNotesFrm', function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1059, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
			$form = $(this);
			var isSelectAll = 0;
			if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $(this).find('input[name="note_element_notes"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please add note.' });
				return false;
			}
			var data = $(this).serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition;
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					$("#editNoteElementModal").modal('hide');
					$("#csrEditProcessModal").modal('hide');
					$.blockUI( block_config );
					window.location.reload();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});
		$('body').on('click', '.deleteNoteElementBtn[data-noteelem]', function(){
			var thisBtn = $(this);
			Swal({
				title: 'Are you sure?',
				text: "Are you sure you want to delete note?",
				type: 'warning',
				showCancelButton: true,
				confirmButtonText: 'Yes'
			}).then((result) => {
				if (result.value) {
					var thisElementId = thisBtn.attr('data-noteelem');
					$form = $('body').find('#deleteNoteElementNotesFrm');
					$form.find('input[name="note_element_delete_notes_hidden"]').val( $('input[name="noteElemSelectNotes'+ thisElementId +'"]').val() );
					var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1059, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
					var isSelectAll = 0;
					if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
						isSelectAll = 1;
					}else{
						isSelectAll = 0;
					}
					if( $form.find('input[name="note_element_delete_notes_hidden"]').val() == "" ){
						swalToast({ type: 'error', title: 'Please add note.' });
						return false;
					}
					var data = $form.serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition;
					$.blockUI( block_config );
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							swalToast({ type: 'success', title: obj.msg });
							$("#csrEditProcessModal").modal('hide');
							$.blockUI( block_config );
							window.location.reload();
						}else{
							swalToast({ type: 'error', title: obj.msg });
							$.unblockUI();
						}
					});
				}
			});
		});
		$('body').on('click', '.addNewNoteElementBtn', function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1059, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'default' } };
			$form = $('#addnewNoteElementNotesFrm');
			var isSelectAll = 0;
			if( $('#tokenholder_table_sa input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $('body').find('input[name="addnewNoteElementNotes"]').val() == "" || typeof $('body').find('input[name="addnewNoteElementNotes"]') === "undefined" ){
				swalToast({ type: 'error', title: 'Please add note.' });
				return false;
			}
			var data = $form.serialize() + '&addnewNoteElementNotes='+ $('body').find('input[name="addnewNoteElementNotes"]').val() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition;
			$('#csrEditProcessModal').block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					$("#csrEditProcessModal").modal('hide');
					$.blockUI( block_config );
					window.location.reload();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$('#csrEditProcessModal').unblock();
			});
			return false;
		});
	}
	var ma_data_url = "<?php echo $ma_csrlist_data_url ?>";
	if( $('#tokenholder_table_ma').length > 0 ){
		var $tableThMa = $('#tokenholder_table_ma');
		$tableThMa.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: ma_data_url,
			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( $('#tokenholder_sa_addresslist').length > 0 ){
		var address_list_data_url = "<?php echo $address_list_data_url ?>";
		var $tableThSaAddress = $('#tokenholder_sa_addresslist');
		$tableThSaAddress.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: address_list_data_url,
			queryParams: function (p) {
				// console.dir( 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();
				}
		  	}
		});
	}
	var distribution_url = "<?php echo $distribution_url ?>";
	if( $('#tokenholder_distribution_table').length > 0 ){
		var $tableDistribution = $('#tokenholder_distribution_table');
		$tableDistribution.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: distribution_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// 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();
				}
		  	}
		});
	}
	var distribution_10_url = "<?php echo $distribution_10_url ?>";
	if( $('#tokenholder_distribution_10_table').length > 0 ){
		var $tableDistribution = $('#tokenholder_distribution_10_table');
		$tableDistribution.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: distribution_10_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// 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( $('#tokenholder_sa_retirement_table').length > 0 ){
		var sa_retirement_url = "<?php echo $sa_retirement_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableDistribution = $('#tokenholder_sa_retirement_table');
		$tableDistribution.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: sa_retirement_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('body').find('.modelpop_notes').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#sa_pending_review_logourl').length > 0 ){
		var sa_pending_review_url = "<?php echo $sa_pending_review_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tablePendinReview = $('#sa_pending_review_logourl');
		$tablePendinReview.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: sa_pending_review_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
		
		let dateFormatLogoReview = 'DD/MM/YYYY';
		$('input.bootstrap-table-filter-control-last_update[type="search"]')
		.daterangepicker({
				autoUpdateInput: false,
				locale: {
					format: dateFormatLogoReview,
					separator: ' - ',
					firstDay: 1
				},
				opens: 'left',
				cancelButtonClasses: 'btn-default'
			},
		);
		jQuery('input.bootstrap-table-filter-control-last_update[type="search"]').on('apply.daterangepicker', function(ev, picker) {
			$(this).val(picker.startDate.format(dateFormatLogoReview) + ' - ' + picker.endDate.format(dateFormatLogoReview));
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-last_update').trigger(eve);
		});
		$('input.bootstrap-table-filter-control-last_update[type="search"]').on('cancel.daterangepicker', function(ev, picker) {
			$(this).val('');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('.bootstrap-table-filter-control-last_update').trigger(eve);
		});
	}
	//5078 code
	if( $('#tokenholder_distribution_weekly_table').length > 0 ){
		var distribution_weekly_table_url = "<?php echo $distribution_weekly_table_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWeeklyTableDistribution = $('#tokenholder_distribution_weekly_table');
		$tableWeeklyTableDistribution.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: distribution_weekly_table_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				/* if( $('body').find('.modelpop_notes').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}else if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				} */
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	//4966
	if( $('#csr_address_pending_review').length > 0 ){
		var csr_address_pending_review_url = "<?php echo $csr_address_pending_review_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tablePendinReview = $('#csr_address_pending_review');
		$tablePendinReview.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_address_pending_review_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#csr_lsh_pending_review').length > 0 ){
		var csr_lsh_pending_review_url = "<?php echo $csr_lsh_pending_review_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tablePendinReview = $('#csr_lsh_pending_review');
		$tablePendinReview.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_lsh_pending_review_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	// kyc/kyb
	if( $('#csr_kyb_pending_review').length > 0 ){
		var csr_kyb_pending_review_url = "<?php echo $csr_kyb_pending_review_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tablePendinReview = $('#csr_kyb_pending_review');
		$tablePendinReview.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_kyb_pending_review_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
			},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	//5690
	if( $('#csr_kyc_pending_review').length > 0 ){
		var csr_kyc_pending_review_url = "<?php echo $csr_kyc_pending_review_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tablePendinReview = $('#csr_kyc_pending_review');
		$tablePendinReview.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_kyc_pending_review_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	//5753
	if( $('#csr_withdraw_requests').length > 0 ){
		var csr_withdraw_requests_url = "<?php echo $csr_withdraw_requests_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWithdrawRequests = $('#csr_withdraw_requests');
		var params = {};
		var filterByConditionUsername = {};
		var thisRows = [];
		var isSelectAll = 0;
		$tableWithdrawRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_withdraw_requests_url,
			searchOnEnterKey: true,
			queryParams: function (p) {
				params = p.filter;
				if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
					isSelectAll = 1;
				}else{
					isSelectAll = 0;
				}
				filterByConditionUsername = convertFormToJSON( '#filter_by_username' );
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					isSelectAll: isSelectAll,
					'filterByConditionUsername': filterByConditionUsername,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				$('#withdrawal_request_wizard_opener').removeClass('disabled').prop('disabled', false);
				$('#withdrawal_request_approve_selected').removeClass('disabled').prop('disabled', false);
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
				if( $('body').find('#csr_withdraw_requests thead th.username .username_filter_info').length <= 0 ){
					$('body').find('#csr_withdraw_requests thead th.username .th-inner').after('<div class="username_filter_info"></div>');
				}
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
				$('#withdrawal_request_wizard_opener').addClass('disabled').prop('disabled', true);
				$('#withdrawal_request_approve_selected').addClass('disabled').prop('disabled', true);
			}
		});
		$('select[name="filter_condition_type_username"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_username');
			if( condition_type == 'none' ){
				$('body').find('.select2_username').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_username_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_username_bulk').show();
				$('body').find('.select2_username').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_username').removeClass('hide');
				$('#filter_condition_value_username_bulk').hide();
			}
		});
		$('body').on('change', 'input[name="toggleWDAll"]', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#csr_withdraw_requests thead th .filter-control .search-input:first').trigger(eve);
			var isSelectAll = 0;
			if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
		});
		$('body').on('click', 'button.withdrawal_request_wizard_opener', function(){
			var withdrawRequestStep = cipscript.withdrawRequestStep;
			if( withdrawRequestStep > 0 ){
				// go_to_x_step_withdraw_request( withdrawRequestStep );
				$('#withdrawalRequestModal').modal({backdrop: 'static',keyboard: false});
			}else{
				var $tableWithdrawRequests = $('#csr_withdraw_requests');
				var isSelectAll = 0;
				if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
					isSelectAll = 1;
				}else{
					isSelectAll = 0;
				}

				var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

				var withdrawRequestIds = [];
				$('#csr_withdraw_requests .rowiddata:checked').each(function(){
					withdrawRequestIds.push($(this).val());
				});

				if( $.isEmptyObject(withdrawRequestIds) ){
					swalToast({ type: 'error', title: 'Please select withdrawal requests' });
					return false;
				}

				var data = { 'action' : 'checkingCsrWRequestDelivery', 'thisParams' : params, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRWalletRequestDeliveryyX_'); ?>", 'withdrawRequestIds' : withdrawRequestIds };
				$.blockUI(block_config);
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						$('#withdrawalRequestModal .process_withdrawal_requests_summary_section').html('');
						$('#withdrawalRequestModal').modal({backdrop: 'static',keyboard: false});
						$('#withdrawalRequestModal .process_withdrawal_requests_summary_section').html( obj.html );
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					$.unblockUI();
				});
			}
			return false;
		});

		$(document).on('click','#withdrawal_request_approve_selected',function(){

			if($('table#csr_withdraw_requests input.rowiddata:checked').length > 0){

				var selectedWithdrawRequestIds = [];
				var isValide = true;
				$('#csr_withdraw_requests .rowiddata:checked').each(function(){
					selectedWithdrawRequestIds.push($(this).val());
					if($(this).attr('data-withdrawalstatus') == 'Pending')
					{
						isValide = false;
					}
				});
				if(!isValide)
				{
					swalToast({ type: 'error', title: 'Please selected under review request only' });
					return false;
				}

				$('#approve_selected_withdraw_request_frm .approve_label').html('Are you sure you want to move these ('+selectedWithdrawRequestIds.length+') requests to the pending withdrawal request?');
				
				$("#approveWithdrawRequestSelectedModal").modal({backdrop: 'static',keyboard: false});				
			}else{
				swalToast({ type: 'error', title: 'Please select records' });
			}

			return false;

		});

		$(document).on('submit','#approve_selected_withdraw_request_frm',function(){
			$form = $(this);
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			if( $form.find('input[name="user_ga_otp"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please enter the authentication code' });
				return false;
			}
			
			var isSelectAll = 0;
			if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}

			var selectedWithdrawRequestIds = [];
			$('#csr_withdraw_requests .rowiddata:checked').each(function(){
				selectedWithdrawRequestIds.push($(this).val());
			});

			var data = $(this).serialize();
			data += '&thisParams='+params;
			data += '&filterByConditionUsername='+filterByConditionUsername;
			data += '&isSelectAll='+isSelectAll;
			data += '&selectedWithdrawRequestIds='+selectedWithdrawRequestIds;
			
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					$('#approve_selected_withdraw_request_frm').bootstrapTable('refresh');
					$('#approve_selected_withdraw_request_frm input#user_ga_otp').val('')
					$("#approveWithdrawRequestSelectedModal").modal('hide');
					var selector = $('table#csr_withdraw_requests input.form-control.search-input')
					let eve = jQuery.Event("keyup");
					eve.which = 13
					eve.keyCode = 13
					selector.trigger(eve);
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});

		$('body').on('click', 'button.csr_withdrawal_requests_download', function(){
			var isSelectAll = 0;
			if( $('#csr_withdraw_requests input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

			var withdrawRequestIds = [];
			$('#csr_withdraw_requests .rowiddata:checked').each(function(){
				withdrawRequestIds.push($(this).val());
			});

			if( $.isEmptyObject(withdrawRequestIds) ){
				swalToast({ type: 'error', title: 'Please select withdrawal requests' });
				return false;
			}

			var $getVisibleColumns = $tableWithdrawRequests.bootstrapTable('getVisibleColumns').map(function (it) { return it.field });

			var data = { 'action' : 'downloadingCsrWDeliveryRequests', 'thisParams' : params, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyDownloadCSRWalletRequestDeliveryyX_'); ?>", 'withdrawRequestIds' : withdrawRequestIds, 'getVisibleColumns' : $getVisibleColumns };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
				var downloadLink = document.createElement("a");
				var fileData = ['\ufeff'+response];
				var blobObject = new Blob([response],{
					type: "application/csv;charset=UTF-8;"
				});
				var url = URL.createObjectURL(blobObject);
				downloadLink.href = url;
				downloadLink.download = "CSR-Withdrawal-Request-" + date + " " + time + ".csv";

				document.body.appendChild(downloadLink);
				downloadLink.click();
				document.body.removeChild(downloadLink);
				$.unblockUI();
			});
			return false;
		});
		if( $('.sa_withdrawal_request_wizard').length > 0 ){
			var block_config_spinner = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var current_fs, next_fs, previous_fs; //fieldsets
			var opacity;
			var current = 1;
			var steps = $('body').find(".sa_withdrawal_request_wizard fieldset").length;
			setProgressBarWRW(current);
			$('body').on("click",".next_wrw", function(event){
				var this_next = $(this);
				current_fs = $(this).closest('fieldset');
				next_fs = $(this).closest('fieldset').next();
				// console.log( current );

				var $form = $('body').find('.sa_withdrawal_request_wizard');
				var data = $form.serialize();

				if( current == 1 ){
					$form.block( block_config_spinner );

					var withdrawRequestIds = [];
					var withdrawRequestQuery = '';
					$('#csr_withdraw_requests .rowiddata:checked').each(function(){
						withdrawRequestIds.push($(this).val());
						withdrawRequestQuery += "&withdrawRequestIds[]=" + $(this).val();
					});

					if( $.isEmptyObject(withdrawRequestIds) ){
						swalToast({ type: 'error', title: 'Please select withdrawal requests' });
						return false;
					}

					data = data + '&isExportProcess=1&thisParams='+params+'&filterByConditionUsername='+filterByConditionUsername+'&isSelectAll='+isSelectAll+withdrawRequestQuery;
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							// $('.sa_withdrawal_request_wizard .download_link').html( obj.download_link );
							setTimeout(() => {
								$(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
								next_fs.show();
								current_fs.animate({opacity: 0}, {
									step: function(now) {
										opacity = 1 - now;

										current_fs.css({
											'display': 'none',
											'position': 'relative'
										});
										next_fs.css({'opacity': opacity});
									},
									duration: 500
								});
								setProgressBarWRW(++current);
								// $('body').find('.download_link a')[0].click();
								if( $('body').find('.sa_withdrawal_request_wizard .step_1 .cancel_wrw').length <= 0 ){
									$('.sa_withdrawal_request_wizard .step_1 .otp_section').append('<input type="button" name="download" class="download_wrw action-button" value="Download"><input type="button" name="cancel" class="cancel_wrw action-button" value="Cancel" />');
								}
							}, 200);
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
						/* var isJson = false;
						try {
							jQuery.parseJSON(response);
							isJson = true;
						} catch(error) {
						}
						// var responseType = jQuery.parseJSON( response );
						// console.log( typeof responseType );
						if( isJson == true ){
							var obj = JSON.parse( response );
							if( obj.error == 1 ){
								swalToast({ type: 'error', title: obj.msg });
								$form.unblock();
							}
						}else{

							var today = new Date();
							var date = today.getFullYear() + "_" + String(today.getMonth() + 1).padStart(2, '0') + "_" + today.getDate();
							// var date = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear();
							// var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
							var time = today.getHours() + "_" + today.getMinutes();

							var downloadLink = document.createElement("a");
							var fileData = ['\ufeff'+response];

							var blobObject = new Blob([response],{
								type: "application/csv;charset=UTF-8;"
							});


							var url = URL.createObjectURL(blobObject);
							downloadLink.href = url;
							downloadLink.download = "CSR_withdrawal_" + date + "_" + time + ".csv";

							document.body.appendChild(downloadLink);
							downloadLink.click();
							document.body.removeChild(downloadLink);
							setTimeout(() => {
								$(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
								next_fs.show();
								current_fs.animate({opacity: 0}, {
									step: function(now) {
										opacity = 1 - now;

										current_fs.css({
											'display': 'none',
											'position': 'relative'
										});
										next_fs.css({'opacity': opacity});
									},
									duration: 500
								});
								setProgressBarWRW(++current);
								$form.unblock();
							}, 2000);
						} */


					});

				}
				/* else if( current == 2 ){
					$form.block( block_config_spinner );
					data = data + '&isdistribution_takes_place=1';
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							$('.distribution_takes_place_response').html('');
							$('.distribution_takes_place_response').html( obj.responseHtml );
							if( $('body').find('.sa_withdrawal_request_wizard .step_2 .cancel_wrw').length <= 0 ){
								$('.sa_withdrawal_request_wizard .step_2 .next_wrw').after('<input type="button" name="cancel" class="cancel_wrw action-button" value="Cancel" />');
							}
							$(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarWRW(++current);
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
					});

				} */
				else if( current == 2 ){
					$(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.animate({opacity: 0}, {
						step: function(now) {
							opacity = 1 - now;
							current_fs.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs.css({'opacity': opacity});
						},
						duration: 500
					});
					setProgressBarWRW(++current);
					/* if( $form.find('input[name="user_ga_otp"]').val() == "" ){
						swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
						return false;
					}
					$form.block( block_config_spinner );
					data = data + '&isCompleteProcess=1';
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							$('.update_withdraw_request_response').html('');
							$('.update_withdraw_request_response').html( obj.responseHtml );
							this_next.hide();
							$('body').find('.cancel_wrw').hide();
							$(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarWRW(++current);
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
					}); */

				}else if( current == 3 ){
					if( $form.find('input[name="sa_txnhash"]').val() == "" ){
						swalToast({ type: 'error', title: 'Please enter transaction hash.' });
						return false;
					}
					if( $form.find('input[name="sa_txnhash"]').val() != "" ){
						var txnhash = $form.find('input[name="sa_txnhash"]').val();
						let regex = /^0x([A-Fa-f0-9]{64})$/;
						if( regex.test( txnhash ) !== true ){
							swalToast({ type: 'error', title: 'Please enter valid transaction hash.' });
							return false;
						}
					}
					if( $form.find('input[name="user_complete_ga_otp"]').val() == "" ){
						swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
						return false;
					}
					$form.block( block_config_spinner );
					data = data + '&isCompleteProcess=1';
					$.post(cipscript.ajax_url, data, function(response) {
						var obj = JSON.parse( response );
						if( obj.error == 0 ){
							$('.update_withdraw_request_response').html('');
							$('.update_withdraw_request_response').html( obj.responseHtml );
							this_next.hide();
							$('body').find('.step_2 .action-button').hide().remove();
							$('body').find('.step_2 .complete_2fa_form').hide().remove();
							$('body').find('.step_2 .form-card').after('<input type="button" name="close" class="close_wrw action-button" value="Close" />');
							$('body').find('#csr_withdraw_requests input').not(':button,:submit,:reset,:hidden').val('');
							let eve = jQuery.Event("keyup");
							eve.which = 13
							eve.keyCode = 13
							$('#csr_withdraw_requests thead th .filter-control .search-input:first').trigger(eve);
							/* $(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
							next_fs.show();
							current_fs.animate({opacity: 0}, {
								step: function(now) {
									opacity = 1 - now;

									current_fs.css({
										'display': 'none',
										'position': 'relative'
									});
									next_fs.css({'opacity': opacity});
								},
								duration: 500
							});
							setProgressBarWRW(++current); */
						}else{
							swalToast({ type: 'error', title: obj.msg });
						}
						$form.unblock();
					});

				}else{
					/* $(".sa_withdrawal_request_wizard #progressbar li").eq( $(".sa_withdrawal_request_wizard fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.animate({opacity: 0}, {
						step: function(now) {
							opacity = 1 - now;
							current_fs.css({
								'display': 'none',
								'position': 'relative'
							});
							next_fs.css({'opacity': opacity});
						},
						duration: 500
					});
					setProgressBarWRW(++current); */
				}
			});
			$('body').on("click",".previous_wrw", function(){
				current_fs = $(this).closest('fieldset');
				previous_fs = $(this).closest('fieldset').prev();
				// console.log( current );
				$(".sa_withdrawal_request_wizard #progressbar li").eq($(".sa_withdrawal_request_wizard fieldset").index(current_fs)).removeClass("active");
				previous_fs.show();
				current_fs.animate({opacity: 0}, {
					step: function(now) {
						opacity = 1 - now;
						current_fs.css({
						'display': 'none',
						'position': 'relative'
						});
						previous_fs.css({'opacity': opacity});
					},
					duration: 500
				});
				setProgressBarWRW(--current);
			});
			function setProgressBarWRW(curStep){
				var percent = parseFloat(100 / steps) * curStep;
				percent = percent.toFixed();
				$('body').find(".sa_withdrawal_request_wizard .progress-bar").css("width",percent+"%")
			}
			$('#withdrawalRequestModal').on('show.bs.modal', function (event) {
				var withdrawRequestStep = cipscript.withdrawRequestStep;
				if( withdrawRequestStep > 0 ){
					go_to_x_step_withdraw_request( withdrawRequestStep );
				}
			});
			function go_to_x_step_withdraw_request( gotoStep = 0 ){
				for (let step = 0; step < (gotoStep - 1 ); step++) {
					var $next_button = $('.step_'+step).find('.next_wrw');

					var current_fs = $next_button.parent();
					var next_fs = $next_button.parent().next();
					$(".sa_withdrawal_request_wizard #progressbar li").eq( $("fieldset").index(next_fs) ).addClass("active");
					next_fs.show();
					current_fs.css({
						'display': 'none',
						'position': 'relative'
					});
					next_fs.css({'opacity': opacity});
					setProgressBarWRW(++current);
				}
			}
			$('body').on("click",".cancel_wrw", function(){

				var $form = $('body').find('.sa_withdrawal_request_wizard');
				if( $form.find('input[name="user_ga_otp"]').val() == "" ){
					swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
					return false;
				}
				//is 2fa check process
				var data = $form.serialize();
				data = data + '&isCancelProcess=1&isCancelProcessCheck2fa=1';
				$form.block( block_config_spinner );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){

						Swal({
							title: 'You are canceling a withdrawal. You MUST NOT distribute this withdrawal file on Token Award.',
							text: "",
							showCancelButton: true,
							confirmButtonText: 'Yes',
						}).then((result) => {
							if (result.value) {
								var data = $form.serialize();
								data = data + '&isCancelProcess=1&isCancelProcessCheck2faValue='+obj.authCode;
								$form.block( block_config_spinner );
								$.post(cipscript.ajax_url, data, function(response) {
									var objRes = JSON.parse( response );
									if( objRes.error == 0 ){
										swalToast({ type: 'success', title: objRes.msg }).then(function(){ window.location.reload(); });
										$("#withdrawalRequestModal").modal('hide');
										setTimeout(() => {
											$.blockUI(block_config_kyc);
										}, 1000);
									}else{
										swalToast({ type: 'error', title: objRes.msg });
									}
									$form.unblock();
								});
							}
						});

					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					$form.unblock();
				});
			});
			$('body').on("click",".cancel_last_wrw", function(){

				var $form = $('body').find('.sa_withdrawal_request_wizard');
				if( $form.find('input[name="user_complete_ga_otp"]').val() == "" ){
					swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
					return false;
				}
				//is 2fa check process
				var data = $form.serialize();
				data = data + '&isCancelProcess=1&stage=complete&isCancelProcessCheck2fa=1';
				$form.block( block_config_spinner );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){

						Swal({
							title: 'You are canceling a withdrawal. You MUST NOT distribute this withdrawal file on Token Award.',
							text: "",
							showCancelButton: true,
							confirmButtonText: 'Yes',
						}).then((result) => {
							if (result.value) {
								var data = $form.serialize();
								data = data + '&isCancelProcess=1&stage=complete&isCancelProcessCheck2faValue='+obj.authCode;
								$form.block( block_config_spinner );
								$.post(cipscript.ajax_url, data, function(response) {
									var objRes = JSON.parse( response );
									if( objRes.error == 0 ){
										swalToast({ type: 'success', title: objRes.msg }).then(function(){ window.location.reload(); });
										$("#withdrawalRequestModal").modal('hide');
										setTimeout(() => {
											$.blockUI(block_config_kyc);
										}, 1000);
									}else{
										swalToast({ type: 'error', title: objRes.msg });
									}
									$form.unblock();
								});
							}
						});

					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					$form.unblock();
				});
			});
			$('body').on("click",".download_wrw", function(){
				var $form = $('body').find('.sa_withdrawal_request_wizard');
				if( $form.find('input[name="user_ga_otp"]').val() == "" ){
					swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
					return false;
				}
				var data = $form.serialize();
				data = data + '&isDownloadProcess=1';
				$form.block( block_config_spinner );
				$.post(cipscript.ajax_url, data, function(response) {
					var obj = JSON.parse( response );
					if( obj.error == 0 ){

						$('.sa_withdrawal_request_wizard .download_link').html( obj.download_link );
						$form.find('input[name="user_ga_otp"]').val('');
						$('body').find('.download_link a')[0].click();
						setTimeout(() => {
							$('body').find('.download_link a').remove();
							$('.sa_withdrawal_request_wizard .step_1 .next_wrw').removeClass('disabled');
							$('.sa_withdrawal_request_wizard .step_1 .next_wrw').prop('disabled', false);
							$('.sa_withdrawal_request_wizard .step_2 .next_wrw').removeClass('disabled');
							$('.sa_withdrawal_request_wizard .step_2 .next_wrw').prop('disabled', false);
							if( $('body').find('.sa_withdrawal_request_wizard .step_2 .cancel_last_wrw').length <= 0 ){
								$('.sa_withdrawal_request_wizard .step_2 .next_wrw').before('<input type="button" name="cancel" class="cancel_last_wrw action-button" value="Cancel" />');
							}
						}, 300);
					}else{
						swalToast({ type: 'error', title: obj.msg });
					}
					$form.unblock();
				});
			});
			$('body').on("click",".close_wrw", function(){
				$("#withdrawalRequestModal").modal('hide');
				window.location.reload();
			});
		}

		//store toggle column
		let lsname = '-hideColumn-csr_withdraw_requests'
		let hideColumn = JSON.parse(localStorage.getItem(lsname)) || [];
		let th = $tableWithdrawRequests.find('thead tr th');
		th.each(function (index) {
			let attrTitle = $(this).attr('data-field')
			if (hideColumn.includes(attrTitle)) {
				$tableWithdrawRequests.bootstrapTable('hideColumn', attrTitle);
			}
		})
		$tableWithdrawRequests.on("column-switch.bs.table", function (e, field, checked) {
			if (checked && hideColumn.includes(field)) {
				// remove form local storage
				const index = hideColumn.indexOf(field);
				if (index > -1) {
					hideColumn.splice(index, 1);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			} else if (!checked) {
				if (hideColumn.includes(field)) {} else {
					hideColumn.push(field);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			}
		});
		$("body").on("change", ".toggle-all", function () {
			let $this = $(this);
			let div = $this.parent().parent()[0];
			$(div).find("input[type=checkbox]").each(function (index) {
				let checked = $(this).is(":checked");
				let field = $(this).attr("data-field");
				if (checked && hideColumn.includes(field)) {
					// remove form local storage
					const index = hideColumn.indexOf(field);
					if (index > -1) {
						hideColumn.splice(index, 1);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				} else if (!checked) {
					if (hideColumn.includes(field)) {
						// hands up nothing needed
					} else {
						// add in LS for nexttime
						hideColumn.push(field);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				}
			});
		});
		//store toggle column

	}
	if( $('#tokenholder_wallet_delivery').length > 0 ){
		var tokenholder_wallet_delivery_url = "<?php echo $tokenholder_wallet_delivery_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWithdrawRequests = $('#tokenholder_wallet_delivery');
		var params = {};
		var filterByCondition = {};
		var filterByConditionPoolRef = {};
		var filterByConditionDistributionWeek = {};
		var filterByConditionUsername = {};
		var thisRows = [];
		var isSelectAll = 0;
		$tableWithdrawRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: tokenholder_wallet_delivery_url,
			// searchTimeOut:1000,
			searchOnEnterKey: true,
			queryParams: function (p) {
				params = p.filter;
				if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
					isSelectAll = 1;
				}else{
					isSelectAll = 0;
				}
				filterByCondition = convertFormToJSON( '#filter_by_notes' );
				filterByConditionPoolRef = convertFormToJSON( '#filter_by_pool_ref' );
				filterByConditionDistributionWeek = convertFormToJSON( '#filter_by_distribution_week' );
				filterByConditionUsername = convertFormToJSON( '#filter_by_username' );

				filterByConditionParsed = JSON.parse( filterByCondition );
				if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
					$('.clear_all_csr_holder').hide();
				}

				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					isSelectAll: isSelectAll,
					'filterByCondition': filterByCondition,
					'filterByConditionPoolRef': filterByConditionPoolRef,
					'filterByConditionDistributionWeek': filterByConditionDistributionWeek,
					'filterByConditionUsername': filterByConditionUsername,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				/* if( $('body').find('#tokenholder_wallet_delivery .keep-open').length > 0 ){
					if( $('body').find('.keep-open .dropdown-item-marker input[data-field="rowiddata"]').length > 0 ){
						$('body').find('.keep-open .dropdown-item-marker input[data-field="rowiddata"]').parent('label').remove();
					}
				} */
				$('.filter-control input.search-input').prop('readonly',false);
				$('.filter-control select.form-control').removeClass('pointerEno');
				$('.csr_delivery').removeClass('disabled').prop('disabled', false);
				$('.csr_delivery_to_saving').removeClass('disabled').prop('disabled', false);
				if( $('body').find('#tokenholder_wallet_delivery thead th.notes_external .note_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery thead th.notes_external .th-inner').after('<div class="note_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery thead th.pool_ref .pool_ref_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery thead th.pool_ref .th-inner').after('<div class="pool_ref_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery thead th.text_10 .distribution_week_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery thead th.text_10 .th-inner').after('<div class="distribution_week_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery thead th.username .username_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery thead th.username .th-inner').after('<div class="username_filter_info"></div>');
				}
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
				$('.filter-control select.form-control').addClass('pointerEno');
				$('.total_amount_due_label').html('-');
				$('.total_selected_amount_due_label').html('-');
				$('.csr_delivery').addClass('disabled').prop('disabled', true);
				$('.csr_delivery_to_saving').addClass('disabled').prop('disabled', true);
				$('.csr_partial_delivery').addClass('disabled').prop('disabled', true);
				filterByConditionParsed = JSON.parse( filterByCondition );
				if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
					$('.clear_all_csr_holder').hide();
				}else{
					$('.clear_all_csr_holder').show();
				}
			},
			onLoadSuccess: function( search ){
				/* if( $('body').find('#tokenholder_wallet_delivery').length > 0 ){
					if( $('body').find('.keep-open .dropdown-item-marker input[data-field="rowiddata"]').length > 0 ){
						$('body').find('.keep-open .dropdown-item-marker input[data-field="rowiddata"]').parent('label').remove();
					}
				} */
			}
		});
		//store toggle column
		let lsname = '-hideColumn-tokenholder_wallet_delivery'
		let hideColumn = JSON.parse(localStorage.getItem(lsname)) || [];
		let th = $tableWithdrawRequests.find('thead tr th');
		th.each(function (index) {
			let attrTitle = $(this).attr('data-field')
			if (hideColumn.includes(attrTitle)) {
				$tableWithdrawRequests.bootstrapTable('hideColumn', attrTitle);
			}
		})
		$tableWithdrawRequests.on("column-switch.bs.table", function (e, field, checked) {
			if (checked && hideColumn.includes(field)) {
				// remove form local storage
				const index = hideColumn.indexOf(field);
				if (index > -1) {
					hideColumn.splice(index, 1);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			} else if (!checked) {
				if (hideColumn.includes(field)) {} else {
					hideColumn.push(field);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			}
		});
		$("body").on("change", ".toggle-all", function () {
			let $this = $(this);
			let div = $this.parent().parent()[0];
			$(div).find("input[type=checkbox]").each(function (index) {
				let checked = $(this).is(":checked");
				let field = $(this).attr("data-field");
				if (checked && hideColumn.includes(field)) {
					// remove form local storage
					const index = hideColumn.indexOf(field);
					if (index > -1) {
						hideColumn.splice(index, 1);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				} else if (!checked) {
					if (hideColumn.includes(field)) {
						// hands up nothing needed
					} else {
						// add in LS for nexttime
						hideColumn.push(field);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				}
			});
		});
		//store toggle column
		$('select[name="filter_condition_type"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('input[name="filter_condition_value"]');
			if( condition_type == 'none' || condition_type == 'is_empty' || condition_type == 'is_not_empty' ){
				$filter_condition_value.hide();
				$filter_condition_value.val('');
			}else{
				$filter_condition_value.show();
			}
		});

		$('select[name="filter_condition_type_pool_ref"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_pool_ref');
			if( condition_type == 'none' ){
				$('body').find('.select2_pool_ref').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_pool_ref_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('body').find('.select2_pool_ref').addClass('hide');
				$('#filter_condition_value_pool_ref_bulk').show();
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_pool_ref').removeClass('hide');
				$('#filter_condition_value_pool_ref_bulk').hide();
			}
		});

		$('select[name="filter_condition_type_distribution_week"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_distribution_week');
			if( condition_type == 'none' ){
				$('body').find('.select2_distribution_week').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_distribution_week_before').val('');
				$('#filter_condition_value_distribution_bulk').val('');
			}else if( condition_type == 'weeks_before' ){
				$('#filter_condition_value_distribution_week_before').show();
				$('#filter_condition_value_distribution_bulk').hide();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').show();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_distribution_week').removeClass('hide');
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').hide();
			}
		});

		$('select[name="filter_condition_type_username"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_username');
			if( condition_type == 'none' ){
				$('body').find('.select2_username').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_username_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_username_bulk').show();
				$('body').find('.select2_username').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_username').removeClass('hide');
				$('#filter_condition_value_username_bulk').hide();
			}
		});
		$('body').on('change', 'input[name="toggleWDAll"]', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#tokenholder_wallet_delivery thead th .filter-control .search-input:first').trigger(eve);
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var $partialDeliveryFrmElem = $('#partialDeliveryFrm');
			$partialDeliveryFrmElem.find('input[name="isSelectAll"]').val( isSelectAll );
		});
		$('body').on('click', 'button.csr_delivery', function(){
			var $tableWithdrawRequests = $('#tokenholder_wallet_delivery');
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'checkingCsrWDelivery', 'thisParams' : params, 'filterByCondition': filterByCondition, 'filterByConditionPoolRef': filterByConditionPoolRef, 'filterByConditionDistributionWeek': filterByConditionDistributionWeek, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRWalletDeliveryyX_'); ?>" };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#csrDeliveryModal .csrDeliveryBody').html('');
					$('#csrDeliveryModal').modal({backdrop: 'static',keyboard: false});
					$('#csrDeliveryModal .csrDeliveryBody').html( obj.html );
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$.unblockUI();
			});
			return false;
		});
		$('body').on('click', 'button.csr_delivery_to_saving', function(){
			var $tableWithdrawRequests = $('#tokenholder_wallet_delivery');
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'checkingCsrWDeliveryToSaving', 'thisParams' : params, 'filterByCondition': filterByCondition, 'filterByConditionPoolRef': filterByConditionPoolRef, 'filterByConditionDistributionWeek': filterByConditionDistributionWeek, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRWalletDeliverToSavingyyX_'); ?>" };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					$('#csrDeliveryToSavingModal .csrDeliveryToSavingBody').html('');
					$('#csrDeliveryToSavingModal').modal({backdrop: 'static',keyboard: false});
					$('#csrDeliveryToSavingModal .csrDeliveryToSavingBody').html( obj.html );
				}else{
					Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
					// swalToast({ type: 'error', title: obj.msg });
				}
				$.unblockUI();
			});
			return false;
		});
		$('body').on('click', 'button.csr_delivery_partial_pre', function(){
			var $tableWithdrawRequests = $('#tokenholder_wallet_delivery');
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'checkingPrePartialCsrWDelivery', 'thisParams' : params, 'filterByCondition': filterByCondition, 'filterByConditionPoolRef': filterByConditionPoolRef, 'filterByConditionDistributionWeek': filterByConditionDistributionWeek, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckPrePartialCSRWalletDeliveryyX_'); ?>" };
			$.blockUI(block_config);
			var $partialDeliverElement = $('.csr_delivery_partial_pre');
			var $partialDeliveryFrmElem = $('#partialDeliveryFrm');
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){

					var partial_delivery_total = obj.total;
					if( obj.total > 0 && obj.total <= 15 ){
						// $partialDeliverElement.attr('data-original-title', 'For partial delivery you will confirm amounts to be delivered on the next page.').tooltip();
						// $partialDeliverElement.removeClass('disabled').prop('disabled', false);
						$partialDeliveryFrmElem.find('input[name="partialDeliveryIds"]').val( obj.partialDeliverIds );
						$partialDeliveryFrmElem.find('input[name="isSelectAll"]').val( isSelectAll );
						$partialDeliveryFrmElem.submit();
					}else{
						// $partialDeliverElement.attr('data-original-title', 'Partial Delivery only available for small delivery selections of under 15 rows.').tooltip();
						// $partialDeliverElement.addClass('disabled').prop('disabled', true);
						$partialDeliveryFrmElem.find('input[name="partialDeliveryIds"]').val('');
					}
				}else{
					swalToast({ type: 'error', title: obj.msg });
					$partialDeliveryFrmElem.find('input[name="partialDeliveryIds"]').val('');
				}
				$.unblockUI();
			});
			return false;
		});
		$('body').on('click', 'button.csr_delivery_download', function(){
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'downloadingCsrWDelivery', 'thisParams' : params, 'filterByCondition': filterByCondition, 'filterByConditionPoolRef': filterByConditionPoolRef, 'filterByConditionDistributionWeek': filterByConditionDistributionWeek, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRWalletDeliveryyX_'); ?>" };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
				var downloadLink = document.createElement("a");
				var fileData = ['\ufeff'+response];
				var blobObject = new Blob([response],{
					type: "application/csv;charset=UTF-8;"
				});

				var url = URL.createObjectURL(blobObject);
				downloadLink.href = url;
				downloadLink.download = "CSRHolder-Delivery-" + date + " " + time + ".csv";

				document.body.appendChild(downloadLink);
				downloadLink.click();
				document.body.removeChild(downloadLink);
				$.unblockUI();
			});
			return false;
		});
		$("#csrDeliveryModal").on('hide.bs.modal', function () {
			$('#csrDeliveryModal .csrDeliveryBody').html('');
		});
		$('body').on('submit', '#csrwalletdelivery_frm', function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$form = $(this);
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $(this).find('input[name="sasm_ga_otp"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
				return false;
			}

			$formDelivery = $('#csrwalletdelivery_frm');

			var data = $(this).serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition+'&filterByConditionPoolRef='+filterByConditionPoolRef+'&filterByConditionDistributionWeek='+filterByConditionDistributionWeek+'&filterByConditionUsername='+filterByConditionUsername+'&get_wallet_delivery_data=yes';
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, async function(response) {
				var obj = JSON.parse( response );
				console.log( obj );
				if( obj.error == 0 ){

					$('.csrwalletdelivery_process_response').append('<li class="list-group-item d-block align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'<div class="total_process_split_append_log_counter">'+obj.totalmsg+'</div><div class="process_split_append_log_counter"></div></li>');

					var promisesAppend = [];
					for (let icsv = 1; icsv <= obj.total_paged; icsv++) {
						var isError = false;
						var data = new FormData( $formDelivery[0] );
						data.append("wallet_delivering_data", 'yes');
						data.append("page_id", icsv);
						data.append("total_paged", obj.total_paged);

						data.append("thisParams", params);
						data.append("isSelectAll", isSelectAll);
						data.append("filterByCondition", filterByCondition);
						data.append("filterByConditionPoolRef", filterByConditionPoolRef);
						data.append("filterByConditionDistributionWeek", filterByConditionDistributionWeek);
						data.append("filterByConditionUsername", filterByConditionUsername);

						var requestAppend = await $.ajax({
							url: cipscript.ajax_url,
							type: 'post',
							data: data,
							processData: false,
							contentType: false,
							timeout: 0,
							async: true,
							success : async function(response){
								var obj = $.parseJSON(response);
								// console.log( obj );
								if( obj.error == 0 ){
									$('body').find('.process_split_append_log_counter').append(obj.msg);

									if( obj.isLastPage == 'yes' ){
										//Append completer, after check user status and update status loop start
										swalToast({ type: 'success', title: obj.msg2 });

										$('body').find('.csrwalletdelivery_process_response').after( '<p class="mt-2"><b>' + obj.msg2 + '</b></p>' );

										$('body .wallet_delivery_complete_ok_btn').show();
										$('body #csrwalletdelivery_frm input').prop('disabled', true);

										/* setTimeout(() => {
											$("#csrDeliveryModal").modal('hide');
											window.location.reload();
										}, 4000); */
									}

								}else{
									$('.csrwalletdelivery_process_response').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-danger badge-pill" data-toggle="tooltip" data-placement="top" title="'+obj.msg2+'"><i class="fa fa-check-"></i></span>'+obj.msg+'</li>');
									isError = true;
								}
								$('[data-toggle="tooltip"]').tooltip();
							}
						});
						if( isError == true ){
							csr_split_spinner.hide();
							buttonAppend.prop('disabled', false);
							buttonCancelAppend.prop('disabled', false);
							break;
						}
						promisesAppend.push(requestAppend);
					}
					Promise.all(promisesAppend).then(responseList => {
						// console.dir( responseList );
						$('.csrwalletdelivery_process_response').append('<li class="list-group-item d-flex align-items-center"><span class="mr-3 badge badge-info badge-pill" data-toggle="tooltip" data-placement="top" title="Wallet deliveries  completed."><i class="fa fa-check-"></i></span>Wallet deliveries completed.</li>');
						$('[data-toggle="tooltip"]').tooltip();
						if( isError ){
							swalToast({ type: 'error', title: obj.msg });
						}else{

						}
						// csr_split_spinner.hide();
					});

				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});

		$('body').on('submit', '#csrwalletdeliverytosaving_frm', function(){
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$form = $(this);
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $(this).find('input[name="sasm_ds_ga_otp"]').val() == "" ){
				swalToast({ type: 'error', title: 'Please enter 6-digit google authenticator code.' });
				return false;
			}
			var data = $(this).serialize() + '&thisParams='+params+'&isSelectAll='+isSelectAll+'&filterByCondition='+filterByCondition+'&filterByConditionPoolRef='+filterByConditionPoolRef+'&filterByConditionDistributionWeek='+filterByConditionDistributionWeek+'&filterByConditionUsername='+filterByConditionUsername;
			$form.block( block_config );
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){
					swalToast({ type: 'success', title: obj.msg });
					$("#csrDeliveryToSavingModal").modal('hide');
					window.location.reload();
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$form.unblock();
			});
			return false;
		});
		/* if( typeof params  !== "undefined" ){
		} */
	}
	if( $('#tokenholder_wallet_delivery_report').length > 0 ){
		var tokenholder_wallet_delivery_report_url = "<?php echo $tokenholder_wallet_delivery_report_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWithdrawRequests = $('#tokenholder_wallet_delivery_report');
		var params = {};
		var filterByCondition = {};
		var filterByConditionPoolRef = {};
		var filterByConditionDistributionWeek = {};
		var filterByConditionUsername = {};
		var thisRows = [];
		var isSelectAll = 0;
		$tableWithdrawRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: tokenholder_wallet_delivery_report_url,
			// searchTimeOut:1000,
			searchOnEnterKey: true,
			queryParams: function (p) {
				params = p.filter;
				filterByCondition = convertFormToJSON( '#filter_by_notes' );
				filterByConditionPoolRef = convertFormToJSON( '#filter_by_pool_ref' );
				filterByConditionDistributionWeek = convertFormToJSON( '#filter_by_distribution_week' );
				filterByConditionUsername = convertFormToJSON( '#filter_by_username' );

				filterByConditionParsed = JSON.parse( filterByCondition );
				if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
					$('.clear_all_csr_holder').hide();
				}

				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					'filterByCondition': filterByCondition,
					'filterByConditionPoolRef': filterByConditionPoolRef,
					'filterByConditionDistributionWeek': filterByConditionDistributionWeek,
					'filterByConditionUsername': filterByConditionUsername,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
				$('.filter-control select.form-control').removeClass('pointerEno');
				$('.csr_delivery').removeClass('disabled').prop('disabled', false);
				if( $('body').find('#tokenholder_wallet_delivery_report thead th.notes_external .note_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery_report thead th.notes_external .th-inner').after('<div class="note_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery_report thead th.pool_ref .pool_ref_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery_report thead th.pool_ref .th-inner').after('<div class="pool_ref_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery_report thead th.text_10 .distribution_week_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery_report thead th.text_10 .th-inner').after('<div class="distribution_week_filter_info"></div>');
				}
				if( $('body').find('#tokenholder_wallet_delivery_report thead th.username .username_filter_info').length <= 0 ){
					$('body').find('#tokenholder_wallet_delivery_report thead th.username .th-inner').after('<div class="username_filter_info"></div>');
				}
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
				$('.filter-control select.form-control').addClass('pointerEno');
				$('.total_amount_due_label').html('-');
				$('.total_selected_amount_due_label').html('-');
				$('.csr_delivery').addClass('disabled').prop('disabled', true);
				$('.csr_partial_delivery').addClass('disabled').prop('disabled', true);
				filterByConditionParsed = JSON.parse( filterByCondition );
				if( filterByConditionParsed.filter_condition_type === 'none' && typeof params === "undefined" ){
					$('.clear_all_csr_holder').hide();
				}else{
					$('.clear_all_csr_holder').show();
				}
			},
			onLoadSuccess: function( search ){
			}
		});
		$('select[name="filter_condition_type"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('input[name="filter_condition_value"]');
			if( condition_type == 'none' || condition_type == 'is_empty' || condition_type == 'is_not_empty' ){
				$filter_condition_value.hide();
				$filter_condition_value.val('');
			}else{
				$filter_condition_value.show();
			}
		});

		$('select[name="filter_condition_type_pool_ref"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_pool_ref');
			if( condition_type == 'none' ){
				$('body').find('.select2_pool_ref').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_pool_ref_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('body').find('.select2_pool_ref').addClass('hide');
				$('#filter_condition_value_pool_ref_bulk').show();
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_pool_ref').removeClass('hide');
				$('#filter_condition_value_pool_ref_bulk').hide();
			}
		});

		$('select[name="filter_condition_type_distribution_week"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_distribution_week');
			if( condition_type == 'none' ){
				$('body').find('.select2_distribution_week').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_distribution_week_before').val('');
				$('#filter_condition_value_distribution_bulk').val('');
			}else if( condition_type == 'weeks_before' ){
				$('#filter_condition_value_distribution_week_before').show();
				$('#filter_condition_value_distribution_bulk').hide();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').show();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_distribution_week').removeClass('hide');
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').hide();
			}
		});

		$('select[name="filter_condition_type_username"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_username');
			if( condition_type == 'none' ){
				$('body').find('.select2_username').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_username_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_username_bulk').show();
				$('body').find('.select2_username').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_username').removeClass('hide');
				$('#filter_condition_value_username_bulk').hide();
			}
		});
		$('body').on('click', 'button.csr_delivery_report_download', function(){
			var isSelectAll = 0;
			if( $('#tokenholder_wallet_delivery_report input[name="toggleWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			var data = { 'action' : 'downloadingCsrWDeliveryReport', 'thisParams' : params, 'filterByCondition': filterByCondition, 'filterByConditionPoolRef': filterByConditionPoolRef, 'filterByConditionDistributionWeek': filterByConditionDistributionWeek, 'filterByConditionUsername': filterByConditionUsername, 'isSelectAll' : isSelectAll, '_micro' : "<?php echo wp_create_nonce('_XyCheckCSRWalletDeliveryReportDownloadyX_'); ?>" };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var today = new Date();
				var date = today.getDate() + "-" + (today.getMonth()+1) + "-" + today.getFullYear();
				var time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
				var downloadLink = document.createElement("a");
				var fileData = ['\ufeff'+response];
				var blobObject = new Blob([response],{
					type: "application/csv;charset=UTF-8;"
				});
				var url = URL.createObjectURL(blobObject);
				downloadLink.href = url;
				downloadLink.download = "Wallet-Delivery-Report-" + date + " " + time + ".csv";

				document.body.appendChild(downloadLink);
				downloadLink.click();
				document.body.removeChild(downloadLink);
				$.unblockUI();
			});
			return false;
		});
	}
	if( $('#csr_transaction_history_deposit').length > 0 ){
		var tokenholder_csr_transaction_history_deposit_url = "<?php echo $tokenholder_csr_transaction_history_deposit_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWithdrawRequests = $('#csr_transaction_history_deposit');
		var params = {}
		$tableWithdrawRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: tokenholder_csr_transaction_history_deposit_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				if( $('[data-toggle-column="tooltip"]').length > 0 ){
					$('[data-toggle-column="tooltip"]').tooltip({ boundary: 'window' });
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#csr_transaction_history_withdrawals').length > 0 ){
		var tokenholder_csr_transaction_history_withdrawals_url = "<?php echo $tokenholder_csr_transaction_history_withdrawals_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableWithdrawRequests = $('#csr_transaction_history_withdrawals');
		var params = {}
		$tableWithdrawRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: tokenholder_csr_transaction_history_withdrawals_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip({ boundary: 'window' });
				}
				if( $('[data-toggle-column="tooltip"]').length > 0 ){
					$('[data-toggle-column="tooltip"]').tooltip({ boundary: 'window' });
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#cip_supportagent_users_list').length > 0 ){
		var cip_supportagent_users_list_url = "<?php echo $cip_supportagent_users_list_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableSupportagentUsersList = $('#cip_supportagent_users_list');
		var params = {}
		$tableSupportagentUsersList.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_supportagent_users_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			// stickyHeaderOffsetY: stickyHeaderOffset,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#cip_completed_withdrawals_list').length > 0 ){
		var cip_completed_withdrawals_list_url = "<?php echo $cip_completed_withdrawals_list_url ?>";
		// console.log( cip_completed_withdrawals_list_url );
		var $tableCompletedWithdrawalsList = $('#cip_completed_withdrawals_list');
		var params = {}
		$tableCompletedWithdrawalsList.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_completed_withdrawals_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});

		$(document).on('click','#export-completed-withdrawals-btn', function () {
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$.blockUI(block_config);
            var $table = $('#cip_completed_withdrawals_list');

		    // Get current options (pagination, sorting, etc.)
		    var options = $table.bootstrapTable('getOptions');

		    // Get current data (applied filters, search, pagination)
		    var data = $table.bootstrapTable('getData', {useCurrentPage: true});

		    // Extract filter values manually
		    var filters = {};
		    $table.find('thead th').each(function () {
		        var field = $(this).data('field');
		        var $input = $(this).find('.filter-control input, .filter-control select');
		        if ($input.length > 0 && $input.val() != '') {
		            filters[field] = $input.val();
		        }
		    });

		    // Prepare parameters for export, excluding keys with null or empty values
		    var params = {};

		    // Add pagination details if they exist
		    if (options.pageSize) {
		        params.limit = options.pageSize;
		    }
		    if (options.pageNumber) {
		        params.offset = options.pageSize * (options.pageNumber - 1);
		    }

		    // Add sorting details if they exist
		    if (options.sortName) {
		        params.sort = options.sortName;
		    }
		    if (options.sortOrder) {
		        params.order = options.sortOrder;
		    }

		    // Add filters if they exist and are not empty
		    if (Object.keys(filters).length > 0) {
		        params.columnfilter = JSON.stringify(filters);
		    }

		    // Add action to params
		    params.action = 'cip_completed_withdrawals_list_export';

	    	// Build the URL by appending the parameters
		    var downloadUrl = cipscript.ajax_url + '?action=cip_completed_withdrawals_list_export';

		    // Loop through params to add them to the URL
		    $.each(params, function (key, value) {
		        if (value !== null && value !== undefined && value !== '') {
		            downloadUrl += '&' + key + '=' + encodeURIComponent(value);
		        }
		    });

			window.location.href = downloadUrl; 
			$.unblockUI();

	    });
	}
	if( $('#cip_completed_withdrawals_all_list').length > 0 ){
		var cip_completed_withdrawals_all_list_url = "<?php echo $cip_completed_withdrawals_all_list_url ?>";

		var $tableCompletedWithdrawalsAllList = $('#cip_completed_withdrawals_all_list');
		var params = {}
		$tableCompletedWithdrawalsAllList.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_completed_withdrawals_all_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});

		$(document).on('click','#export-completed-withdrawals-all-btn', function () {
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
			$.blockUI(block_config);
            var $table = $('#cip_completed_withdrawals_all_list');

		    // Get current options (pagination, sorting, etc.)
		    var options = $table.bootstrapTable('getOptions');

		    // Get current data (applied filters, search, pagination)
		    var data = $table.bootstrapTable('getData', {useCurrentPage: true});

		    // Extract filter values manually
		    var filters = {};
		    $table.find('thead th').each(function () {
		        var field = $(this).data('field');
		        var $input = $(this).find('.filter-control input, .filter-control select');
		        if ($input.length > 0 && $input.val() != '') {
		            filters[field] = $input.val();
		        }
		    });

		    // Prepare parameters for export, excluding keys with null or empty values
		    var params = {};

		    // Add pagination details if they exist
		    if (options.pageSize) {
		        params.limit = options.pageSize;
		    }
		    if (options.pageNumber) {
		        params.offset = options.pageSize * (options.pageNumber - 1);
		    }

		    // Add sorting details if they exist
		    if (options.sortName) {
		        params.sort = options.sortName;
		    }
		    if (options.sortOrder) {
		        params.order = options.sortOrder;
		    }

		    // Add filters if they exist and are not empty
		    if (Object.keys(filters).length > 0) {
		        params.columnfilter = JSON.stringify(filters);
		    }

		    // Add action to params
		    params.action = 'cip_completed_withdrawals_all_list_export';

	    	// Build the URL by appending the parameters
		    var downloadUrl = cipscript.ajax_url + '?action=cip_completed_withdrawals_all_list_export';

		    // Loop through params to add them to the URL
		    $.each(params, function (key, value) {
		        if (value !== null && value !== undefined && value !== '') {
		            downloadUrl += '&' + key + '=' + encodeURIComponent(value);
		        }
		    });

			window.location.href = downloadUrl; 
			$.unblockUI();

	    });
	}
	if( $('#cip_simple_notes_management_list').length > 0 ){
		var cip_simple_notes_management_list_url = "<?php echo $cip_simple_notes_management_list_url ?>";
		// console.log( cip_simple_notes_management_list_url );
		var $tableCompletedWithdrawalsList = $('#cip_simple_notes_management_list');
		var params = {}
		$tableCompletedWithdrawalsList.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_simple_notes_management_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	if( $('#cip_sms_alert_management_list').length > 0 ){
		var cip_sms_alert_management_list_url = "<?php echo $cip_sms_alert_management_list_url ?>";
		// console.log( cip_sms_alert_management_list_url );
		var $tableSmsAlert = $('#cip_sms_alert_management_list');
		var params = {}
		$tableSmsAlert.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_sms_alert_management_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}

	// header notice table loader

	if( $('#cip_notice_header_setting_table').length > 0 ){
		var cip_notice_header_setting_url = "<?php echo $cip_notice_header_setting_url ?>";
		// console.log( cip_sms_alert_management_list_url );
		var $tableSmsAlert = $('#cip_notice_header_setting_table');
		var params = {}
		$tableSmsAlert.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_notice_header_setting_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}
	// header notice table loader

	if( $('#cip_amount_wallet_table').length > 0 ){
		var cip_amount_wallet_table_url = "<?php echo $cip_amount_wallet_table_url ?>";
		var $tableAmountWalletTable = $('#cip_amount_wallet_table');
		$tableAmountWalletTable.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_amount_wallet_table_url,
			queryParams: function (p) {
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
		  	},
			onSearch: function( search ){
			}
		});
	}
	if( $('table#countries_management').length > 0 ){
		var countries_management_table_url = "<?php echo $countries_management_table_url ?>";
		var $countriesManagementTable = $('#countries_management');
		$countriesManagementTable.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: countries_management_table_url,
			queryParams: function (p) {
				return {
					search: p.search,
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
		});
	}

	/**
	 * Withdrawal adress block bootstrap table initialize
	 */
	if( $('table#cip_withdrawal_block_address_list').length > 0 ){
		var cip_withdrawal_block_address_list_table_url = "<?php echo $cip_withdrawal_block_address_list_table_url ?>";
		var $countriesManagementTable = $('#cip_withdrawal_block_address_list');
		$countriesManagementTable.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: cip_withdrawal_block_address_list_table_url,
			searchOnEnterKey: true,
			queryParams: function (p) {
				return {
					search: p.search,
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip({ boundary: 'window' })
				}
		  	},
			stickyHeader: true,
		});
	}

	/**
	 * corporate_users_list bootstrap table initialize
	 */
	if( $('#corporate_users_list').length > 0 ){
		var corporate_users_list_url = "<?php echo $corporate_users_list_url ?>";
		var $tableCorporateUsersList = $('#corporate_users_list');
		var params = {}
		$tableCorporateUsersList.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: corporate_users_list_url,
			searchTimeOut:1000,
			queryParams: function (p) {
				params = p.filter;
				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
				};
			},
			stickyHeader: true,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
			}
		});
	}

	/**
	 *  corporate_user_request_withdrawal_list bootstrap table initialize
	 */
	if( $('#corporate_user_request_withdrawal_list').length > 0 ){
		var corporate_user_request_withdrawal_list_url = "<?php echo $corporate_user_request_withdrawal_list_url ?>";
		var wpadminbar = isNaN( parseInt( $('#wpadminbar').height() ) ) ? 0 : parseInt( $('#wpadminbar').height() ) ;
		stickyHeaderOffset = wpadminbar;
		var $tableCorporateUserWithdrawalRequests = $('#corporate_user_request_withdrawal_list');
		var params = {};
		var filterByCondition = {};
		var filterByConditionPoolRef = {};
		var filterByConditionDistributionWeek = {};
		var filterByConditionUsername = {};
		var thisRows = [];
		var isSelectAll = 0;
		var tokenType = 'csr';
		$tableCorporateUserWithdrawalRequests.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: corporate_user_request_withdrawal_list_url,
			searchOnEnterKey: true,
			queryParams: function (p) {
				params = p.filter;
				if( $('#corporate_user_request_withdrawal_list input[name="toggleCURWDAll"]').is(':checked') ){
					isSelectAll = 1;
				}else{
					isSelectAll = 0;
				}

				if( $('#csr_corporate_user_summary_wr select[name="token_type"]').val() == 'csr25' ){
					tokenType = 'csr25';
				}else{
					tokenType = 'csr';
				}


				return {
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					isSelectAll: isSelectAll,
					tokenType: tokenType,
				};
			},
			stickyHeader: false,
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip();
				}
				$('.filter-control input.search-input').prop('readonly',false);
				$('.filter-control select.form-control, #csr_corporate_user_summary_wr select').removeClass('pointerEno');
				$('.csr_delivery').removeClass('disabled').prop('disabled', false);
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
				$('.filter-control select.form-control, #csr_corporate_user_summary_wr select').addClass('pointerEno');
				$('.total_amount_due_label').html('-');
				$('.total_selected_amount_due_label').html('-');
				$('.csr_delivery').addClass('disabled').prop('disabled', true);
			},
			onLoadSuccess: function( search ){
			}
		});
		//store toggle column
		let lsname = '-hideColumn-corporate_user_request_withdrawal_list'
		let hideColumn = JSON.parse(localStorage.getItem(lsname)) || [];
		let th = $tableCorporateUserWithdrawalRequests.find('thead tr th');
		th.each(function (index) {
			let attrTitle = $(this).attr('data-field')
			if (hideColumn.includes(attrTitle)) {
				$tableCorporateUserWithdrawalRequests.bootstrapTable('hideColumn', attrTitle);
			}
		})
		$tableCorporateUserWithdrawalRequests.on("column-switch.bs.table", function (e, field, checked) {
			if (checked && hideColumn.includes(field)) {
				// remove form local storage
				const index = hideColumn.indexOf(field);
				if (index > -1) {
					hideColumn.splice(index, 1);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			} else if (!checked) {
				if (hideColumn.includes(field)) {} else {
					hideColumn.push(field);
					localStorage.setItem(lsname, JSON.stringify(hideColumn))
				}
			}
		});
		$("body").on("change", ".toggle-all", function () {
			let $this = $(this);
			let div = $this.parent().parent()[0];
			$(div).find("input[type=checkbox]").each(function (index) {
				let checked = $(this).is(":checked");
				let field = $(this).attr("data-field");
				if (checked && hideColumn.includes(field)) {
					// remove form local storage
					const index = hideColumn.indexOf(field);
					if (index > -1) {
						hideColumn.splice(index, 1);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				} else if (!checked) {
					if (hideColumn.includes(field)) {
						// hands up nothing needed
					} else {
						// add in LS for nexttime
						hideColumn.push(field);
						localStorage.setItem(
							lsname,
							JSON.stringify(hideColumn)
						);
					}
				}
			});
		});
		$('body').on('change', 'input[name="toggleCURWDAll"]', function(){
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$('#corporate_user_request_withdrawal_list thead th .filter-control .search-input:first').trigger(eve);
			var isSelectAll = 0;
			if( $('#corporate_user_request_withdrawal_list input[name="toggleCURWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
		});
		$('body').on('click', 'button.corporate_user_request_withdrawal', function(){
			var $tableWithdrawRequests = $('#corporate_user_request_withdrawal_list');
			var isSelectAll = 0;
			var tokenType = 'csr';
			if( $('#corporate_user_request_withdrawal_list input[name="toggleCURWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $('#csr_corporate_user_summary_wr select[name="token_type"]').val() == 'csr25' ){
				tokenType = 'csr25';
			}else{
				tokenType = 'csr';
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

			var corporateUsersIds = [];
			$('#corporate_user_request_withdrawal_list .rowiddata:checked').each(function(){
				corporateUsersIds.push($(this).val());
			});

			if( $.isEmptyObject(corporateUsersIds) ){
				swalToast({ type: 'error', title: 'Please select corporate user' });
				return false;
			}

			var data = { 'action' : 'checkingCorporateUserRequestWithdrawals', 'thisParams' : params, 'isSelectAll' : isSelectAll, 'tokenType' : tokenType, '_micro' : "<?php echo wp_create_nonce('_XyCheckCorporateUserRequestWithdrawalsyX_'); ?>", 'corporateUsersIds' : corporateUsersIds };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){

					const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
					for (let i = 1; i < interval_id; i++) {
						window.clearInterval(i);
					}

					$('#csrCorporateUserRequestWithdrawalModal .csrCorporateUserRequestWithdrawalBody').html('');
					$('#csrCorporateUserRequestWithdrawalModal').modal({backdrop: 'static',keyboard: false});
					$('#csrCorporateUserRequestWithdrawalModal .csrCorporateUserRequestWithdrawalBody').html( obj.html );
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$.unblockUI();
			});
			return false;
		});
		$('body').on('click', '#resend_corporate_user_withdrawal_request', function(){
			var $tableWithdrawRequests = $('#corporate_user_request_withdrawal_list');
			var isSelectAll = 0;
			var tokenType = 'csr';
			if( $('#corporate_user_request_withdrawal_list input[name="toggleCURWDAll"]').is(':checked') ){
				isSelectAll = 1;
			}else{
				isSelectAll = 0;
			}
			if( $('#csr_corporate_user_summary_wr select[name="token_type"]').val() == 'csr25' ){
				tokenType = 'csr25';
			}else{
				tokenType = 'csr';
			}
			var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

			var corporateUsersIds = [];
			$('#corporate_user_request_withdrawal_list .rowiddata:checked').each(function(){
				corporateUsersIds.push($(this).val());
			});

			if( $.isEmptyObject(corporateUsersIds) ){
				swalToast({ type: 'error', title: 'Please select corporate user' });
				return false;
			}

			var data = { 'action' : 'checkingCorporateUserRequestWithdrawals', 'thisParams' : params, 'isSelectAll' : isSelectAll, 'tokenType' : tokenType, '_micro' : "<?php echo wp_create_nonce('_XyCheckCorporateUserRequestWithdrawalsyX_'); ?>", 'corporateUsersIds' : corporateUsersIds, 'resend' : 1 };
			$.blockUI(block_config);
			$.post(cipscript.ajax_url, data, function(response) {
				var obj = JSON.parse( response );
				if( obj.error == 0 ){

					const interval_id = window.setInterval(function(){}, Number.MAX_SAFE_INTEGER);
					for (let i = 1; i < interval_id; i++) {
						window.clearInterval(i);
					}

					$('#csrCorporateUserRequestWithdrawalModal .csrCorporateUserRequestWithdrawalBody').html('');
					$('#csrCorporateUserRequestWithdrawalModal').modal({backdrop: 'static',keyboard: false});
					$('#csrCorporateUserRequestWithdrawalModal .csrCorporateUserRequestWithdrawalBody').html( obj.html );
				}else{
					swalToast({ type: 'error', title: obj.msg });
				}
				$.unblockUI();
			});
			return false;
		});

		$("#csrCorporateUserRequestWithdrawalModal").on('hide.bs.modal', function () {
			$('#csrCorporateUserRequestWithdrawalModal .csrCorporateUserRequestWithdrawalBody').html('');
		});

		$('#csr_corporate_user_summary_wr select[name=token_type]').on('change', function(){
			var $emailFilter = $('input.bootstrap-table-filter-control-email[type="search"]');
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$emailFilter.trigger(eve);
		});
	}

	/**
	 * CSR Pool Report bootstrap table initialize
	 */
	if( $('table#csr_pool_report_list').length > 0 ){
		var csr_pool_report_list_table_url = "<?php echo $csr_pool_report_list_table_url ?>";
		var $countriesManagementTable = $('#csr_pool_report_list');
		var params = {};
		var filterByConditionPoolRef = {};
		var filterByConditionDistributionWeek = {};

		$countriesManagementTable.bootstrapTable({
			method: 'post',
			contentType: 'application/x-www-form-urlencoded',
			url: csr_pool_report_list_table_url,
			searchOnEnterKey: true,
			queryParams: function (p) {

				params = p.filter;

				filterByConditionPoolRef = convertFormToJSON( '#filter_by_pool_reference' );
				filterByConditionDistributionWeek = convertFormToJSON( '#filter_by_distribution_week' );

				return {
					search: p.search,
					columnfilter: p.filter,
					limit: p.limit,
					offset: p.offset,
					sort: p.sort,
					order: p.order,
					'filterByConditionPoolRef': filterByConditionPoolRef,
					'filterByConditionDistributionWeek': filterByConditionDistributionWeek,
				};
			},
			onPostBody: function (){
				if( $('[data-toggle-tt="tooltip"]').length > 0 ){
					$('[data-toggle-tt="tooltip"]').tooltip({ boundary: 'window' })
				}
				setTimeout(() => {
					$('.filter-control input.search-input').prop('readonly',false);
					$('.filter-control select.form-control').removeClass('pointerEno');
				}, 600);
				if( $('body').find('#csr_pool_report_list thead th.pool_reference .pool_reference_filter_info').length <= 0 ){
					$('body').find('#csr_pool_report_list thead th.pool_reference .th-inner').after('<div class="pool_reference_filter_info"></div>');
				}
				if( $('body').find('#csr_pool_report_list thead th.distribution_week .distribution_week_filter_info').length <= 0 ){
					$('body').find('#csr_pool_report_list thead th.distribution_week .th-inner').after('<div class="distribution_week_filter_info"></div>');
				}
		  	},
			onSearch: function( search ){
				$('.filter-control input.search-input').prop('readonly',true);
				$('.filter-control select.form-control').addClass('pointerEno');
			},
			stickyHeader: true,
		});

		$('select[name="filter_condition_type_pool_reference"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_pool_reference');
			if( condition_type == 'none' ){
				$('body').find('.select2_pool_reference').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_pool_reference_bulk').val('').hide();
			}else if( condition_type == 'is_exactly_simple' ){
				$('body').find('.select2_pool_reference').addClass('hide');
				$('#filter_condition_value_pool_reference_bulk').show();
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_pool_reference').removeClass('hide');
				$('#filter_condition_value_pool_reference_bulk').hide();
			}
		});

		$('select[name="filter_condition_type_distribution_week"]').on('change', function(){
			var condition_type = $(this).val();
			var $filter_condition_value = $('select#filter_condition_value_distribution_week');
			if( condition_type == 'none' ){
				$('body').find('.select2_distribution_week').addClass('hide');
				$filter_condition_value.val(null).trigger('change');
				$('#filter_condition_value_distribution_week_before').val('');
				$('#filter_condition_value_distribution_bulk').val('');
			}else if( condition_type == 'weeks_before' ){
				$('#filter_condition_value_distribution_week_before').show();
				$('#filter_condition_value_distribution_bulk').hide();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly_simple' ){
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').show();
				$('body').find('.select2_distribution_week').addClass('hide');
			}else if( condition_type == 'is_exactly' ){
				$('body').find('.select2_distribution_week').removeClass('hide');
				$('#filter_condition_value_distribution_week_before').hide();
				$('#filter_condition_value_distribution_bulk').hide();
			}
		});

		var $pool_reference = $('input.bootstrap-table-filter-control-pool_reference[type="search"]');
		$pool_reference.on('click', function(){
			$('#poolRefFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		var $distribution_week = $('input.bootstrap-table-filter-control-distribution_week[type="search"]');
		$distribution_week.on('click', function(){
			$('#DistributionWeekFilterModal').modal({backdrop: 'static',keyboard: false});
		});

		$('.filter_by_pool_reference .filter_csr_ok').on('click', function(){ //pool ref
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$pool_reference.trigger(eve);
			$('#poolRefFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_pool_reference');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_pool_reference"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_pool_reference"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_pool_reference').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_pool_reference_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' ){
				if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.pool_reference_filter_info').text( filterText );

		});
		$('.filter_by_distribution_week .filter_csr_ok').on('click', function(){ //distribution_week text_10
			let eve = jQuery.Event("keyup");
			eve.which = 13
			eve.keyCode = 13
			$distribution_week.trigger(eve);
			$('#DistributionWeekFilterModal').modal('hide');

			var filterNoteForm = $('#filter_by_distribution_week');
			var condition_type_text = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').text();
			var condition_type = filterNoteForm.find('select[name="filter_condition_type_distribution_week"] option:selected').val();
			var condition_type_value = filterNoteForm.find('select#filter_condition_value_distribution_week').val();
			var condition_type_value_before = filterNoteForm.find('#filter_condition_value_distribution_week_before').val();
			var condition_type_value_bulk = filterNoteForm.find('textarea#filter_condition_value_distribution_bulk').val();
			var filterText = condition_type_text;
			if( condition_type_value != "" || condition_type_value_bulk != '' || condition_type_value_before != "" ){
				if( condition_type == 'weeks_before' ){
					filterText += ': '+condition_type_value_before;
				}else if( condition_type == 'is_exactly_simple' ){
					filterText += ': '+condition_type_value_bulk;
				}else{
					filterText += ': '+condition_type_value;
				}
			}
			if( condition_type_text == 'None' ){
				filterText = "";
			}
			$('body').find('.distribution_week_filter_info').text( filterText );

		});

		$('form#filter_by_pool_reference, form#filter_by_distribution_week').keydown(function (e) {
			if (e.keyCode == 13) {
				$('.filter_csr_ok').trigger('click');
				e.preventDefault();
				return false;
			}
		});
		$('.filter_by_pool_reference .filter_csr_cancel').on('click', function(){
			$('#poolRefFilterModal').modal('hide');
		});
		$('.filter_by_distribution_week .filter_csr_cancel').on('click', function(){
			$('#DistributionWeekFilterModal').modal('hide');
		});

		$('.filter_by_pool_reference #filter_condition_value_pool_reference').select2({placeholder: 'Pool Reference',tags: true, selectionCssClass: 'select2_pool_reference hide mt-2', dropdownParent: $('#poolRefFilterModal')});
		$('.filter_by_distribution_week #filter_condition_value_distribution_week').select2({placeholder: 'Distribution Week',tags: true, selectionCssClass: 'select2_distribution_week hide mt-2', dropdownParent: $('#DistributionWeekFilterModal')});

	}

  });
</script>
<?php
}
add_action('wp_ajax_retirement_loader','cip_retirement_loader_cb');
add_action('wp_ajax_nopriv_retirement_loader','cip_retirement_loader_cb');
function cip_retirement_loader_cb(){
	global $wpdb;
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_id = get_current_user_id();
	$user_id = -1;

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement");
	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement");

	$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 = "";
	$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))';
	}
	/*$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		$count = 1;
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'fullname' ){
				$companyEmails = array();
				$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$filterData."%' AND `company_name_toggle` = 1");
				if( $getCompanies ){
					foreach( $getCompanies as $getCompany ){
						$companyEmails[] = $getCompany->email;
					}
				}
				if( !empty( $companyEmails ) ){
					$companyEmail = implode( "','",$companyEmails );
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' OR `email` IN ('".$companyEmail."') )";
				}else{
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' )";
				}
			}else{
				$filter_qry .= ( $filterKey == 'retire_amount' ) ? " AND `$filterKey` = $filterData" : " AND `$filterKey` LIKE '%" . $filterData . "%'";
			}
			// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
			$count++;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}*/
	$amountdata = json_decode( stripslashes( $_REQUEST['amountfilterByConditionPoolRef'] ), true );
	if( !empty( $amountdata ) ){
		$count = 1;
		// foreach( $amountdata as $filterKey => $filterData ){
		// 	if(){

		// 	}
		// 	// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
		// 	$count++;
		// }
		if(isset($amountdata['fullname']) && $amountdata['fullname'] != ""){
			$name_parts = explode(" ", $amountdata['fullname']);
			if(!empty($name_parts[1])){
				$last_name = "OR `last_name` LIKE '%" . $name_parts[1] . "%'";
			}else{
				$last_name = "";
			}
			$companyEmails = array();
			$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$name_parts[0]."%' AND `company_name_toggle` = 1");
			if( $getCompanies ){
				foreach( $getCompanies as $getCompany ){
					$companyEmails[] = $getCompany->email;
				}
			}
			if( !empty( $companyEmails ) ){
				$companyEmail = implode( "','",$companyEmails );
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." OR `email` IN ('".$companyEmail."') )";
			}else{
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." )";
			}
		}

		if(isset($amountdata['eth_address']) && $amountdata['eth_address'] != ""){
			$filter_qry .= " AND `eth_address` LIKE '%" . $amountdata['eth_address'] . "%'";
		}
		if(isset($amountdata['retire_transhash']) && $amountdata['retire_transhash'] != ""){
			$filter_qry .= " AND `retire_transhash` LIKE '%" . $amountdata['retire_transhash'] . "%'";
		}

		// if (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "" && isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` BETWEEN '$start_amount' AND '$end_amount'";
		// }
		// // Check for only start amount (greater than)
		// elseif (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$filter_qry .= " AND `retire_amount` > '$start_amount'";
		// }
		// // Check for only end amount (less than)
		// elseif (isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` < '$end_amount'";
		// }
		if(isset($amountdata['retire_amount_type']) && $amountdata['retire_amount_type'] != ""){
			if(isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != ""){
				$filter_qry .= " AND `retire_amount` ".$amountdata['retire_amount_type']." '".$amountdata['retire_amount_start']."'";
			}
		}

		if (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "" && isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` BETWEEN '$start_amount' AND '$end_amount'";
		}
		// Check for only start amount (greater than)
		elseif (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$filter_qry .= " AND `retire_confirm_date` > '$start_amount'";
		}
		// Check for only end amount (less than)
		elseif (isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` < '$end_amount'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}

	if( isset($_POST['letter']) && $_POST['letter'] != ""){
		$companyEmails = array();
		$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '".$_POST['letter']."%' AND `company_name_toggle` = 1");
		if( $getCompanies ){
			foreach( $getCompanies as $getCompany ){
				$companyEmails[] = $getCompany->email;
			}
		}
		if( !empty( $companyEmails ) ){
			$companyEmail = implode( "','",$companyEmails );
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' OR `email` IN ('".$companyEmail."') )";
		}else{
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' )";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}

	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$user_id = get_current_user_id();

	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';
	$rows = array();
	if( $getRetirements ){
		foreach( $getRetirements as $getRetirement ){
			$row = array();
			$columnsDataVal = '—';
			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>';
			}else{
				$columnsDataVal = '—';
			}

			$retire_transhash = '—';
			if( !empty( $getRetirement->retire_transhash ) ){
				$transhashDataValMask = substr($getRetirement->retire_transhash, 0, 10) . '...' . substr($getRetirement->retire_transhash, -10);
				$retire_transhash = '<a href="'.$endpoint.$getRetirement->retire_transhash.'" target="_blank" class="transhash_view" data-toggle-tt="tooltip" data-placement="top" title="'.$getRetirement->retire_transhash.'" >'.$transhashDataValMask.'</a>';
			}else{
				$retire_transhash = '—';
			}

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

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

			$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$getRetirement->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 = '".$getRetirement->email."' ");
			$member_logo_img = "";
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$hiLine = $getRetirementSetting->company_name;
				}
				if( $getRetirementSetting->status == 1 && !empty( $getRetirementSetting->member_logo ) ){
					$member_logo_img = '<img class="member_logo_img" src="data:image/jpg;charset=utf8;base64,'.base64_encode($getRetirementSetting->member_logo).'" class="img-responsive" />';
					if( !empty( $getRetirementSetting->member_url ) ){
						$member_logo_img = '<a href="'. $getRetirementSetting->member_url .'" target="_blank">'.$member_logo_img.'</a>';
					}
				}
				if( $getRetirementSetting->status == 1 && !empty( $getRetirementSetting->member_url ) ){
					$hiLine = '<a href="'. $getRetirementSetting->member_url .'" target="_blank">'.$hiLine.' <i class="fas fa-external-link-alt"></i></a>';
				}
			}

			$row['member_logo'] = $member_logo_img;
			$row['fullname'] = $hiLine;
			$row['eth_address'] = $columnsDataVal;
			$row['retire_transhash'] = $retire_transhash;
			// $row['retire_transhash'] = $select_abc;
			$row['retire_amount'] = cip_number_format($getRetirement->retire_amount,false);
			$row['retire_confirm_date'] = $retire_confirm_date;
			$rows[] = $row;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_holder_retirement_loader','cip_holder_retirement_loader_cb');
add_action('wp_ajax_nopriv_holder_retirement_loader','cip_holder_retirement_loader_cb');
function cip_holder_retirement_loader_cb(){
	global $wpdb;
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_id = get_current_user_id();
	$user_id = -1;
	$refAccount = ( !empty( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : 0 ;

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement");
	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement");

	$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';
	$eth_address = $_GET['eth_address'];

	$filter_qry = "";
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	$visibility_qry = 'retire_visibility = 3';
	if( is_user_logged_in() ){
		$visibility_qry = '((retire_visibility = 3 OR retire_visibility = 2) OR (email = "'.$refAccount.'" AND retire_visibility = 1))';
	}

	if( !empty( $filters ) ){
		$count = 1;
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'fullname' ){
				$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' )";
			}else{
				$filter_qry .= ( $filterKey == 'retire_amount' ) ? " AND `$filterKey` = $filterData" : " AND `$filterKey` LIKE '%" . $filterData . "%'";
			}
			$count++;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE eth_address = '$eth_address' AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE eth_address = '$eth_address' AND $visibility_qry $filter_qry");
	}

	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE eth_address = '$eth_address' AND $visibility_qry $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$user_id = get_current_user_id();
	$rows = array();
	if( $getRetirements ){
		foreach( $getRetirements as $getRetirement ){
			$row = array();
			$columnsDataVal = '—';
			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>';
			}else{
				$columnsDataVal = '—';
			}

			$retire_transhash = '—';
			if( !empty( $getRetirement->retire_transhash ) ){
				$transhashDataValMask = substr($getRetirement->retire_transhash, 0, 10) . '...' . substr($getRetirement->retire_transhash, -10);
				$retire_transhash = '<p class="transhash_view" data-toggle-tt="tooltip" data-placement="top" title="'.$getRetirement->retire_transhash.'" >'.$transhashDataValMask.'</p>';
			}else{
				$retire_transhash = '—';
			}

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

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

			$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$getRetirement->email."' LIMIT 1 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 = '".$getRetirement->email."' ");
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$hiLine = $getRetirementSetting->company_name;
				}
			}

			$row['fullname'] = $hiLine;
			$row['eth_address'] = $columnsDataVal;
			$row['retire_transhash'] = $retire_transhash;
			// $row['retire_transhash'] = $select_abc;
			$row['retire_amount'] = cip_number_format($getRetirement->retire_amount,true);
			$row['retire_confirm_date'] = $retire_confirm_date;
			$row['token'] = strtoupper( $getRetirement->token );
			$rows[] = $row;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_euvatapi_logs_loader','cip_euvatapi_logs_loader_cb');
add_action('wp_ajax_nopriv_euvatapi_logs_loader','cip_euvatapi_logs_loader_cb');
function cip_euvatapi_logs_loader_cb(){
	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';

	$logTable = $wpdb->prefix.'cip_logs';
	$getLogs = $wpdb->get_results( "SELECT * FROM $logTable WHERE log_type = 'api_track' ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset" );
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE log_type = 'api_track'");

	$rows = array();
	if( $getLogs ){
		$rowCounter = 1;
		foreach( $getLogs as $getLog ){
			$row = array();
			$logsArr = maybe_unserialize( $getLog->logs );
			$logData = "";
			if( is_array( $logsArr ) ){
				foreach( $logsArr as $key => $logArr ){
					$logData .= '<p>'.$key.' : '. $logArr .'</p>';
				}
			}
			$row['id'] = $offset + $rowCounter;
			$row['logs'] = $logData;
			$row['log_type'] = $getLog->log_type;
			$row['_date'] = date_i18n( 'd/m/Y H:i A', strtotime( $getLog->_date ) );
			$rows[] = $row;
			$rowCounter++;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_wallet_api_logs_loader','cip_wallet_api_logs_loader_cb');
// add_action('wp_ajax_nopriv_wallet_api_logs_loader','cip_wallet_api_logs_loader_cb');
function cip_wallet_api_logs_loader_cb(){
	global $wpdb;

	$logTable = $wpdb->prefix.'cip_logs';
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
// 	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'STR_TO_DATE(`_date`,"%Y-%m-%d %H:%i:%s")';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE log_type != 'api_track'");

	$filter_qry = "";
	$test = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_date' ){
				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 DATE_FORMAT(`$filterKey`,'%Y-%m-%d') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";
				}else{
					$filterDataObj = DateTime::createFromFormat('d/m/Y', $filterData);
					$filterData = $filterDataObj->format('Y-m-d');
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%Y-%m-%d') = '$filterData'";
				}
			}else if( $filterKey == 'user_type'  ){
				if($filterData == 'member'){
					// $filter_qry .= " City = ' ' OR City = 'London'; AND `$filterKey` = ' ' AND `$filterKey` = '" . $filterData . "'";
					$filter_qry .= " AND `$filterKey` = '' OR `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}

			}else if( $filterKey == 'filterByConditionPoolRef' ){
				$filter_qry .= " AND `logs` like '%" . $filterData['filter_condition_type_logs'] . "%'";
				$filter_qry .= " AND `logs` like '%" . $filterData['filter_condition_value_logs_bulk'] . "%'";
			}else {
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}

		}

	}
	$filterByConditionPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );

	if( !empty( $filterByConditionPoolRef ) ){
		foreach( $filterByConditionPoolRef as $filterKey => $filterData ){
			$filter_qry .= " AND `logs` like '%" . $filterData . "%'";
		}
	}
	if($filter_qry != ""){
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $logTable WHERE log_type != 'api_track' $filter_qry");
	}

    if( $orderby == 'id' || $orderby == '_date' ){
        $getLogs = $wpdb->get_results( "SELECT * FROM $logTable WHERE log_type != 'api_track' $filter_qry ORDER BY DATE_FORMAT(`_date`,'%Y-%m-%d %H:%i:%s') $order LIMIT $limit OFFSET $offset" );
    }else{
        $getLogs = $wpdb->get_results( "SELECT * FROM $logTable WHERE log_type != 'api_track' $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset" );
    }

	$rows = array();
	if( $getLogs ){
		$rowCounter = 1;
		foreach( $getLogs as $getLog ){
			$row = array();
			$logsArr = maybe_unserialize( $getLog->logs );
			$logData = "";
			if( is_array( $logsArr ) ){
				foreach( $logsArr as $key => $logArr ){
					$logData .= '<p>'.$key.' : '. $logArr .'</p>';
				}
			}
			// $row['id'] = $offset + $rowCounter;
			$user_type = '—';
			if( $getLog->user_type  == 'sm' ){
				$user_type = __('Support Manager',CIP_TXTDOMAIN);
			}else if( $getLog->user_type  == 'sa' ){
				$user_type = __('Support Agent',CIP_TXTDOMAIN);
			}else if( $getLog->user_type  == 'member' ){
				$user_type = __('Member',CIP_TXTDOMAIN);
			}else if( $getLog->user_type  == 'MAs' ){
				$user_type = __('Member Assitant',CIP_TXTDOMAIN);
			}else if( $getLog->user_type  == 'buyer' ){
				$user_type = __('Buyer',CIP_TXTDOMAIN);
			}else{
				$user_type = __('Member',CIP_TXTDOMAIN);
			}
			/* if( $getLog->log_type == 'setting_option' || $getLog->log_type == 'kyc_setting' || $getLog->log_type == 'retire' ){
			}else{
				$row['logs'] = $getLog->logs;
			} */
			$row['logs'] = nl2br( $getLog->logs );
			$row['log_type'] = $user_type;
			$row['user_type'] = $user_type;
			$getLogDate = "";
			if( DateTime::createFromFormat('d/m/Y H:i:s', $getLog->_date) !== false ){
				try {
					$_date = DateTime::createFromFormat('d/m/Y H:i:s', $getLog->_date);
					$getLogDate = $_date->format('d/m/Y H:i A');
				} catch (\Throwable $th) {
					$getLogDate = '';
				}
			}else if( DateTime::createFromFormat('Y-m-d H:i:s', $getLog->_date) !== false ){
				try {
					$_date = DateTime::createFromFormat('Y-m-d H:i:s', $getLog->_date);
					$getLogDate = $_date->format('d/m/Y H:i A');
				} catch (\Throwable $th) {
					$getLogDate = '';
				}
			}
			$row['_date'] = $getLogDate;
			$rows[] = $row;
			$rowCounter++;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_ma_tokenholder_loader','cip_ma_tokenholder_loader_cb');
function cip_ma_tokenholder_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE ma_enabled = 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';

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE ma_enabled = 1 $filter_qry ORDER BY `id` DESC");
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE ma_enabled = 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$saUserData = get_user_by( 'id', $user_id );
	global $defaultColumnsArr;
	if( $saUserData && in_array( "member_assistant", $saUserData->roles ) ){
		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsSAColumnOption = (array)get_option('cip_column_sa_toggle_columns');
		$columnsArr = array();
		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
			if( empty( $columnsArr ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsSAColumnOption[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}else{
			unset( $defaultColumnsArr['imported_by'] );
			unset( $defaultColumnsArr['import_at'] );
			unset( $defaultColumnsArr['last_update_at'] );
			$columnsArr = $defaultColumnsArr;
		}
	}else{
		unset( $defaultColumnsArr['imported_by'] );
		unset( $defaultColumnsArr['import_at'] );
		unset( $defaultColumnsArr['last_update_at'] );
		$columnsArr = $defaultColumnsArr;
	}
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
						$columnsDataVal = cip_trim_notes( $columnsDataVal );
						$columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 50, '<a href="javascript:void(0);" class="modelpop_notes" data-toggle="modal" data-target="#viewMoreModal" data-id="'.$getCurrentMember->id.'" data-viewmore="'.wpautop( $columnsDataVal ).'" data-toggle-tt1="tooltip" data-placement1="top" title="'.$columnsDataVal150.'" >'.__('...More',CIP_TXTDOMAIN).'</a>' );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}
					if( $columnKey == 'position' ){
						$positionVal = '—';
						$positionText = __('Distribution Position not set... Try back later',CIP_TXTDOMAIN);
						if( $columnsDataVal ){
							$positionVal = $columnsDataVal;
							$positionText = sprintf( __('Distribution Position is set... congratulations you are at position %s in the distribution list',CIP_TXTDOMAIN), $columnsDataVal );
						}
						$columnsDataVal = '<a href="javascript:void(0);" data-id="'.$getCurrentMember->id.'" data-toggle-tt="tooltip" data-placement="top" title="'.$positionText.'" >'.$positionVal.'</a>';
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$editLink = add_query_arg( array(
				'action' => 'edit',
				'id' => $getCurrentMember->id,
			), get_the_permalink( $_REQUEST['pageid'] ) );
			$unVerifyLink = "";
			if( $verified ){
				$unVerifyLink = '<a href="javascript:void(0);" class="unverify_cth ml-2" data-toggle-tt="tooltip" data-placement="top" title="Unverify" data-eth="'.$getCurrentMember->id.'"><i class="fas fa-undo"></i></a>';
			}

			$row['action'] = '<a href="'.$editLink.'" title="edit"><i class="fas fa-edit"></i></a>'.$unVerifyLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_tokenholder_distribution_loader','cip_tokenholder_distribution_loader_cb');
function cip_tokenholder_distribution_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder_distribution_temp';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");

	$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'] : 'asc';

	$filter_qry = "";
	$total_import_label = "";
	$total_import = 0;
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $filter_qry ORDER BY `id` asc");
	}
	$total_import_items = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 ORDER BY `id` asc");
	if( $total_import_items ){
		foreach( $total_import_items as $total_import_item ){
			$total_import += $total_import_item->csr_amount_initial;
		}
	}
	$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableName WHERE 1 AND `eth_address` != ''");
	if( $total_import ){
		$total_import_label = sprintf( __('<b>%s</b><br/>Total CSR wallet address : %s<br/> Total CSR : %s<br/>Unique CSR wallet addresses : %s', CIP_TXTDOMAIN), __('Import Summary',CIP_TXTDOMAIN),$total_items_summery, number_format($total_import), $unique_addresses );
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'reference'				=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'csr_amount_initial'	=>	__('csr_amount_initial', CIP_TXTDOMAIN),
				'csr_amount_issued'		=>	__('csr_amount_issued', CIP_TXTDOMAIN),
				'amount_due'			=>	__('amount_due', CIP_TXTDOMAIN),
				'first_name'			=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'				=>	__('last_name', CIP_TXTDOMAIN),
				'created'				=>	__('created', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'distribution_status'	=>	__('distribution_status', CIP_TXTDOMAIN),
				'member_status'			=>	__('member_status', CIP_TXTDOMAIN),
				'corp_approved'			=>	__('corp_approved', CIP_TXTDOMAIN),
				'notes_external'		=>	__('notes_external', CIP_TXTDOMAIN),
				'pool_ref'				=>	__('pool_ref', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'					=>	$total_items,
		'rows'					=>	$rows,
		'total_import_label'	=>	$total_import_label
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_tokenholder_distribution_10_loader','cip_tokenholder_distribution_10_loader_cb');
function cip_tokenholder_distribution_10_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder_distribution';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0");

	$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'] : 'asc';

	$filter_qry = "";
	$total_issued = 0;
	$total_issued_label = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE `amount_due` > 0  $filter_qry ORDER BY `id` asc");
	}
	$total_issued_items = $wpdb->get_results("SELECT `amount_due` FROM $tableName WHERE `amount_due` > 0  ORDER BY `id` asc");
	if( $total_issued_items ){
		foreach( $total_issued_items as $total_issued_item ){
			$total_issued += $total_issued_item->amount_due;
		}
	}
	$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableName WHERE 1 AND `eth_address` != ''");
	if( $total_issued ){
		$total_issued_label = sprintf( __('<b>%s</b><br/>Total CSR wallet address : %s<br/> Total CSR : %s<br/>Unique CSR wallet addresses : %s', CIP_TXTDOMAIN), __('Distribution Summary',CIP_TXTDOMAIN),$total_items_summery, number_format($total_issued), $unique_addresses );
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE `amount_due` > 0 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'reference'				=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'csr_amount_initial'	=>	__('csr_amount_initial', CIP_TXTDOMAIN),
				'csr_amount_issued'		=>	__('csr_amount_issued', CIP_TXTDOMAIN),
				'amount_due'			=>	__('amount_due', CIP_TXTDOMAIN),
				'first_name'			=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'				=>	__('last_name', CIP_TXTDOMAIN),
				'created'				=>	__('created', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'distribution_status'	=>	__('distribution_status', CIP_TXTDOMAIN),
				'corp_approved'			=>	__('corp_approved', CIP_TXTDOMAIN),
				'week_number'			=>	__('week_number', CIP_TXTDOMAIN),
				'member_status'			=>	__('member_status', CIP_TXTDOMAIN),
				'pool_ref'				=>	__('pool_ref', CIP_TXTDOMAIN),
				'source'				=>	__('source', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'total_issued_label'	=>	$total_issued_label
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_tokenholder_sa_retirement_loader','cip_tokenholder_sa_retirement_loader_cb');
function cip_tokenholder_sa_retirement_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1");
	
	$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 = "";
	$total_issued = 0;
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'retire_visibility'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == 'username' ){
				$filter_qry .= " AND `$filterKey` like '" . $filterData . "%'";
			}else{				
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $filter_qry ORDER BY `id` asc");
	}
	$total_issued_items = $wpdb->get_results("SELECT `csr_amount_issued` FROM $tableName WHERE 1 $filter_qry ORDER BY `id` asc");
	if( $total_issued_items ){
		foreach( $total_issued_items as $total_issued_item ){
			$total_issued += $total_issued_item->csr_amount_issued;
		}
	}
	
	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'	=>	__('username', CIP_TXTDOMAIN),
				'first_name'	=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'	=>	__('last_name', CIP_TXTDOMAIN),
				'token'	=>	__('token', CIP_TXTDOMAIN),
				'retire_amount'	=>	__('csr_retired_amount', CIP_TXTDOMAIN),
				'retire_date'	=>	__('retire_date', CIP_TXTDOMAIN),
				'email'	=>	__('email', CIP_TXTDOMAIN),
				'eth_address'	=>	__('eth_address', CIP_TXTDOMAIN),
				'name_on_the_certificate'	=>	__('name_on_the_certificate', CIP_TXTDOMAIN),
				'retire_visibility'	=>	__('retire_visibility', CIP_TXTDOMAIN),
				'action'	=>	__('action', CIP_TXTDOMAIN),
			);
			$hiLine = $getCurrentMember->first_name . ' ' . $getCurrentMember->last_name;
			
			$getTokenData = $wpdb->get_row("SELECT * FROM $tableTokenHolder WHERE email = '".$getCurrentMember->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 `company_name_toggle`, `company_name`   FROM $tableRetirementSetting WHERE email = '".$getCurrentMember->email."' ");
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$hiLine = $getRetirementSetting->company_name;
				}
			}
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'name_on_the_certificate' ){
						$columnsDataVal = $hiLine;
					}else if( $columnKey == 'retire_visibility' ){
						switch ($getCurrentMember->$columnKey) {
							case '1':
								$columnsDataVal = __('Private', CIP_TXTDOMAIN);
								break;
							case '2':
								$columnsDataVal = __('Restricted', CIP_TXTDOMAIN);
								break;
							case '3':
								$columnsDataVal = __('Public', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}
					if($columnKey == 'retire_amount'){
						if (fmod($columnsDataVal, 1) !== 0.0) {
							$row[$columnKey] = number_format($columnsDataVal,2);
						}else{
							$row[$columnKey] = number_format($columnsDataVal);
						}
					}else{
						$row[$columnKey] = $columnsDataVal;
					}
				}
			}
			$retire_status_og = $getCurrentMember->retire_status;
			if( $retire_status_og == 1 ){
				$pdf_url = add_query_arg( array(
					'retireid'	=>	$getCurrentMember->id,
					'action' => 'retire_pdf',
				), admin_url('admin-ajax.php') );
				$pdf_link = '<a href="'.$pdf_url.'" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="Event Certificate"><i class="fa fa-download" aria-hidden="true"></i></a>';
			}else if( $retire_status_og == 0 ){
				$pdf_link = '<a href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title="Retirement is pending"><i class="fa fa-download" aria-hidden="true"></i></a>';
			}else{
				$pdf_link = '<a href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title="Retirement is incomplete"><i class="fa fa-download" aria-hidden="true"></i></a>';
			}
			$totalRetirementConfirmCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE email = '".$getCurrentMember->email."' AND eth_address = '".$getCurrentMember->eth_address."' AND retire_status = 1 ");
			$totalRetirementPdfLink = "";
			if( $totalRetirementConfirmCount ){
				$total_pdf_url = add_query_arg( array(
					'retireaddress'	=>	$getCurrentMember->eth_address,
					'action' => 'total_retire_pdf',
				), admin_url('admin-ajax.php') );
				$totalRetirementPdfLink = '<a class="fa fa-download mr-2 ml-2 viewRetirementTotal" href="'.$total_pdf_url.'" target="_blank" data-toggle-tt="tooltip" data-placement="top" title=" '. __('Total Retirements',CIP_TXTDOMAIN) . '"></a>';
			}
			$row['action'] = $pdf_link . $totalRetirementPdfLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
//5638
add_action('wp_ajax_sa_pending_review_logourl_loader','cip_sa_pending_review_logourl_loader_cb');
function cip_sa_pending_review_logourl_loader_cb(){
	global $wpdb;
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$tabletoken_holder = $wpdb->prefix.'token_holder';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirementSetting WHERE (( `member_url` != '' AND `member_url` IS NOT NULL ) OR ( `member_logo` != '' AND `member_logo` IS NOT NULL )) ORDER BY `last_update` DESC");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : "`status`=2 desc,`status`=0 desc,`last_update`";
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
	$isDateColumn = array('last_update');

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'username' || $filterKey == 'first_name' || $filterKey == 'last_name' ){
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}else if( $filterKey == 'status' || $filterKey == 'sa_user_id' ){
				$filter_qry .= " AND `$filterKey` = " . $filterData . "";
			}else if( $filterKey == 'last_update' ){
				$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 DATE_FORMAT(`$filterKey`,'%Y-%m-%d') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";
			}else{
				$filter_qry .= " AND rs.`$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(rs.id) FROM `$tableRetirementSetting` rs LEFT JOIN ( SELECT email, username, first_name, last_name FROM `$tabletoken_holder` GROUP BY email ) th ON rs.email = th.email WHERE 1 AND ( (rs.member_url IS NOT NULL AND rs.member_url != '') OR (rs.member_logo IS NOT NULL AND rs.member_logo != '') ) $filter_qry");
	}

	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%Y-%m-%d')";
	}

	$getRetirementSettings = $wpdb->get_results("SELECT rs.*, th.username AS `username`, th.first_name AS `first_name`, th.last_name AS `last_name` FROM `$tableRetirementSetting` rs LEFT JOIN ( SELECT email, username, first_name, last_name FROM `$tabletoken_holder` WHERE ( first_name <> '' AND first_name IS NOT NULL ) GROUP BY email ) th ON rs.email = th.email WHERE 1 AND ( (rs.member_url IS NOT NULL AND rs.member_url != '') OR (rs.member_logo IS NOT NULL AND rs.member_logo != '') ) $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");


	$rows = array();
	if( $getRetirementSettings ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getRetirementSettings as $getRetirementSetting ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'		=>	__('username', CIP_TXTDOMAIN),
				'first_name'	=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'		=>	__('last_name', CIP_TXTDOMAIN),
				'email'			=>	__('email', CIP_TXTDOMAIN),
				'member_url'	=>	__('member_url', CIP_TXTDOMAIN),
				'member_logo'	=>	__('member_logo', CIP_TXTDOMAIN),
				'rejection_msg'	=>	__('rejection_msg', CIP_TXTDOMAIN),
				'status'		=>	__('status', CIP_TXTDOMAIN),
				'last_update'	=>	__('last_update', CIP_TXTDOMAIN),
				'sa_user_id'	=>	__('sa_user_id', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getRetirementSetting->$columnKey;
					if( $columnKey == 'member_logo' ){
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<a href="javascript:void(0);" class="view_attachments_img ml-3" data-toggle-tt="tooltip" data-placement="top" title="View" logo-src="data:image/jpg;charset=utf8;base64,'.base64_encode($columnsDataVal).'">View Logo</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'member_url' ){
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<a href="'. $columnsDataVal .'" target="_blank">'. $columnsDataVal .'</a>';
						}
					}else if( $columnKey == 'status' ){
						switch ($getRetirementSetting->$columnKey) {
							case '0':
								$columnsDataVal = __('Rejected', CIP_TXTDOMAIN);
								break;
							case '1':
								$columnsDataVal = __('Approved', CIP_TXTDOMAIN);
								break;
							case '2':
								$columnsDataVal = __('Pending review', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}else if( $columnKey == 'last_update' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d/m/Y H:i A');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'sa_user_id' ){
						$saUserData = get_user_by( 'id', $columnsDataVal );
						if( $saUserData ){
							$columnsDataVal = $saUserData->user_email;
						}else{
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$approved = $getRetirementSetting->status;
			$encryptId = base64_encode($getRetirementSetting->id . 'CIPLOGOURLAPPROVAL');
			if( $approved == 2 ){
				$row['action'] = '<div class="d-flex justify-content-around"><a href="javascript:void(0);" class="approve_logourl ml-3" data-toggle-tt="tooltip" data-placement="top" title="Approve" data-id="'.$encryptId.'"><i class="fas fa-check-circle"></i></a><a href="javascript:void(0);" class="reject_logourl ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a></div>';
			}else if( $approved == 1 ){
				$row['action'] = '<a href="javascript:void(0);" class="unapprove_logourl ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a>';
			}else if( $approved == 0 ){
				$row['action'] = '<a href="javascript:void(0);" class="approve_logourl ml-3" data-toggle-tt="tooltip" data-placement="top" title="Approve" data-id="'.$encryptId.'"><i class="fas fa-check-circle"></i></a>';
			}else{
				$row['action'] = '-';
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	if( empty( $rows ) ){
		$total_items = 0;
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
//5078 code
add_action('wp_ajax_distribution_weekly_table_loader','cip_distribution_weekly_table_loader_cb');
function cip_distribution_weekly_table_loader_cb(){
	global $wpdb;
	$tableWeeklyDistributionExport = $wpdb->prefix.'weekly_distribution_export';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
	$total_items_summery = $wpdb->get_var("SELECT COUNT(id) FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");

	$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'] : 'asc';

	$filter_qry = "";
	$total_amount_due = 0;
	$total_weekly_label = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == '_user_status' || $filterKey == 'kyc_status' || $filterKey == 'corp_approved'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				// $filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) $filter_qry ORDER BY `id` asc");
	}
	$total_amount_due_items = $wpdb->get_results("SELECT `amount_due` FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) ORDER BY `id` asc");
	if( $total_amount_due_items ){
		foreach( $total_amount_due_items as $total_amount_due_item ){
			$total_amount_due += $total_amount_due_item->amount_due;
		}
	}
	$unique_addresses = $wpdb->get_var("SELECT COUNT(DISTINCT (`eth_address`)) FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' )");
	if( $total_amount_due ){
		$total_weekly_label = sprintf( __('<b>Weekly distribution summary</b><br/>Total CSR address : %s<br/> Total CSR due amount: %s<br/>Unique CSR addresses : %s', CIP_TXTDOMAIN), $total_items_summery, number_format($total_amount_due), $unique_addresses );
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableWeeklyDistributionExport WHERE 1 AND ( `eth_address` IS NOT NULL AND `eth_address` <> '' ) $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	global $defaultColumnsArr;
	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'		=>	__('username', CIP_TXTDOMAIN),
				'reference'		=>	__('reference', CIP_TXTDOMAIN),
				'eth_address'	=>	__('eth_address', CIP_TXTDOMAIN),
				'amount_due'	=>	__('amount_due', CIP_TXTDOMAIN),
				'week_number'	=>	__('week_number', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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.'" >'. $columnsDataVal . '</a>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'total_weekly_label'	=>	$total_weekly_label
	);
	echo wp_json_encode( $out );
	exit;
}
//4966
add_action('wp_ajax_csr_address_pending_review_loader','cip_csr_address_pending_review_loader_cb');
function cip_csr_address_pending_review_loader_cb(){
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableAddressPending = $wpdb->prefix.'csr_address_pending';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableAddressPending WHERE 1 ");

	$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 ){
			$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableAddressPending WHERE 1 $filter_qry");
	}

	$getPendingLists = $wpdb->get_results("SELECT * FROM $tableAddressPending WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");


	$rows = array();
	if( $getPendingLists ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getPendingLists as $getPendingList ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'username'			=>	__('username', CIP_TXTDOMAIN),
				'email'			=>	__('email', CIP_TXTDOMAIN),
				'eth_address'	=>	__('eth_address', CIP_TXTDOMAIN),
				'member_passport'	=>	__('member_passport', CIP_TXTDOMAIN),
				'piece_paper_wallet_address'	=>	__('piece_paper_wallet_address', CIP_TXTDOMAIN),
				// 'piece_paper_the_date'	=>	__('piece_paper_the_date', CIP_TXTDOMAIN),
				'reject_msg'	=>	__('reject_msg', CIP_TXTDOMAIN),
				'status'		=>	__('status', CIP_TXTDOMAIN),
				'user_date'		=>	__('user_date', CIP_TXTDOMAIN),
			);
			$encryptId = base64_encode($getPendingList->id . md5('CIPpassportCIP'));
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getPendingList->$columnKey;
					if( $columnKey == 'eth_address' ){
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<a href="javascript:void(0);">'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'member_passport' || $columnKey == 'piece_paper_wallet_address' ){
						if( !empty( $columnsDataVal ) ){
							// $columnsDataVal = '<img src="data:image/jpg;charset=utf8;base64,'.base64_encode($columnsDataVal).'" class="img-responsive csr_address_review_imgs" />';
							$columnsDataVal = '<a href="javascript:void(0);" class="view_attachments_address '.$columnKey.' ml-3" data-toggle-tt="tooltip" data-placement="top" title="View" data-id="'.$encryptId.'"><i class="fas fa-eye"></i> View image</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'status' ){
						switch ($getPendingList->$columnKey) {
							case '0':
								$columnsDataVal = __('Rejected', CIP_TXTDOMAIN);
								break;
							case '1':
								$columnsDataVal = __('Approved', CIP_TXTDOMAIN);
								break;
							case '2':
								$columnsDataVal = __('Pending review', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}else if( $columnKey == 'user_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$approved = $getPendingList->status;
			if( $approved == 2 ){
				$row['action'] = '<a href="javascript:void(0);" class="approve_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Approve" data-id="'.$encryptId.'"><i class="fas fa-check-circle"></i></a><a href="javascript:void(0);" class="reject_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a>';
			}else if( $approved == 1 ){
				// $row['action'] = '<a href="javascript:void(0);" class="unapprove_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a>';
				$row['action'] = '-';
			}else{
				$row['action'] = '-';
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_csr_lsh_pending_review_loader','cip_csr_lsh_pending_review_loader_cb');
function cip_csr_lsh_pending_review_loader_cb(){
	global $wpdb;
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableLSHPending = $wpdb->prefix.'csr_lsh_pending';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableLSHPending WHERE 1 ");

	$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 ){
			$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableLSHPending WHERE 1 $filter_qry");
	}

	$getPendingLists = $wpdb->get_results("SELECT * FROM $tableLSHPending WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");


	$rows = array();
	if( $getPendingLists ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getPendingLists as $getPendingList ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'email'				=>	__('email', CIP_TXTDOMAIN),
				'username'			=>	__('username', CIP_TXTDOMAIN),
				'eth_address'		=>	__('eth_address', CIP_TXTDOMAIN),
				'member_passport'	=>	__('member_passport', CIP_TXTDOMAIN),
				'piece_paper_wallet_address'	=>	__('piece_paper_wallet_address', CIP_TXTDOMAIN),
				'reject_msg'		=>	__('reject_msg', CIP_TXTDOMAIN),
				'status'			=>	__('status', CIP_TXTDOMAIN),
				'user_date'			=>	__('user_date', CIP_TXTDOMAIN),
			);
			$encryptId = base64_encode($getPendingList->id . md5('CIPSecurityHold'));

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getPendingList->$columnKey;
					if( $columnKey == 'eth_address' ){
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<a href="javascript:void(0);">'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'member_passport' || $columnKey == 'piece_paper_wallet_address' ){
						if( !empty( $columnsDataVal ) ){
							// $columnsDataVal = '<img src="data:image/jpg;charset=utf8;base64,'.base64_encode($columnsDataVal).'" class="img-responsive csr_address_review_imgs" />';
							$columnsDataVal = '<a href="javascript:void(0);" class="view_attachments '.$columnKey.' ml-3" data-toggle-tt="tooltip" data-placement="top" title="View" data-id="'.$encryptId.'"><i class="fas fa-eye"></i> View image</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'status' ){
						switch ($getPendingList->$columnKey) {
							case '0':
								$columnsDataVal = __('Rejected', CIP_TXTDOMAIN);
								break;
							case '1':
								$columnsDataVal = __('Approved', CIP_TXTDOMAIN);
								break;
							case '2':
								$columnsDataVal = __('Pending review', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}else if( $columnKey == 'user_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$approved = $getPendingList->status;
			if( $approved == 2 ){
				$row['action'] = '<a href="javascript:void(0);" class="approve_lsh_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Approve" data-id="'.$encryptId.'"><i class="fas fa-check-circle"></i></a><a href="javascript:void(0);" class="reject_lsh_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a>';
			}else if( $approved == 1 ){
				// $row['action'] = '<a href="javascript:void(0);" class="unapprove_csraddress ml-3" data-toggle-tt="tooltip" data-placement="top" title="Reject" data-id="'.$encryptId.'"><i class="fas fa-times-circle"></i></a>';
				$row['action'] = '-';
			}else{
				$row['action'] = '-';
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
// kyb/kyc
add_action('wp_ajax_csr_kyb_pending_review_loader','cip_csr_kyb_pending_review_loader_cb');
function cip_csr_kyb_pending_review_loader_cb(){
	global $wpdb;
	$tableKyc = $wpdb->prefix.'kyc_data';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type` = 'business'");
	
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : "`status`='pending' desc,`_date`";
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	
	$isDateColumn = array('dob');
	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){

			if ($filterKey === 'lastupdate' || $filterKey === '_date') {
	            
	            $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 DATE_FORMAT(`$filterKey`,'%Y-%m-%d') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";

	        }else
	        {
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
	        }

		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type` = 'business' $filter_qry");
	}
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}
	$getKycLists = $wpdb->get_results("SELECT * FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type` = 'business' $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
	
	
	$rows = array();
	if( $getKycLists ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getKycLists as $getKycList ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'email'			=>	__('email', CIP_TXTDOMAIN),
				'business_name'	=>	__('business_name', CIP_TXTDOMAIN),
				'business_director_first_name'	=>	__('business_director_first_name', CIP_TXTDOMAIN),
				'business_director_last_name'	=>	__('business_director_last_name', CIP_TXTDOMAIN),
				'_date'	=>	__('_date', CIP_TXTDOMAIN),
				'lastupdate'	=>	__('lastupdate', CIP_TXTDOMAIN),
				'status'		=>	__('status', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getKycList->$columnKey;
					if( $columnKey == '_date' || $columnKey == 'lastupdate' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'dob' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'd/m/Y', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'status' ){
						switch ($columnsDataVal) {
							case 'pending':
								$columnsDataVal = __('Pending', CIP_TXTDOMAIN);
								break;
							case 'reject':
								$columnsDataVal = __('Rejected', CIP_TXTDOMAIN);
								break;
							case 'dropped':
								$columnsDataVal = __('Dropped', CIP_TXTDOMAIN);
								break;
							case 'approved':
								$columnsDataVal = __('Approved', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$encryptId = base64_encode($getKycList->id . md5('CIP_kyc_CIP'));
			$viewUrl = add_query_arg( array('view' => $encryptId ), get_the_permalink( $_REQUEST['pageid'] ) );
			$row['action'] = '<a href="'.$viewUrl.'" class=""><i class="fas fa-eye"></i></a>';
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		// 'test'	=>	"SELECT * FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset"
	);
	echo wp_json_encode( $out );
	exit;
}
//5690
add_action('wp_ajax_csr_kyc_pending_review_loader','cip_csr_kyc_pending_review_loader_cb');
function cip_csr_kyc_pending_review_loader_cb(){
	global $wpdb;
	$tableKyc = $wpdb->prefix.'kyc_data';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type`='individual'");
	
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : "`status`='pending' desc,`_date`";
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	
	$isDateColumn = array('dob');
	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if ($filterKey === 'lastupdate' || $filterKey === '_date') {
	            
	            $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 DATE_FORMAT(`$filterKey`,'%Y-%m-%d') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";

	        } elseif ($filterKey === 'dob') {
			    
			    $filterDataMinMax = explode(' - ', $filterData);
			    
			    $filterDataMinMax0 = DateTime::createFromFormat('d/m/Y', $filterDataMinMax[0]);
			    if ($filterDataMinMax0) {
			        $filterDataMinMax0Date = $filterDataMinMax0->format('Y-m-d');
			    } else {
			    	$filterDataMinMax0Date = null;
			    }
			    
			    $filterDataMinMax1 = DateTime::createFromFormat('d/m/Y', $filterDataMinMax[1]);
			    if ($filterDataMinMax1) {
			        $filterDataMinMax1Date = $filterDataMinMax1->format('Y-m-d');
			    } else {
			        $filterDataMinMax1Date = null;
			    }

			    if ($filterDataMinMax0Date && $filterDataMinMax1Date) {
			        $filter_qry .= " AND STR_TO_DATE(`$filterKey`, '%d/%m/%Y') BETWEEN '$filterDataMinMax0Date' AND '$filterDataMinMax1Date'";
			    }

			} else {
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
	        }
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type`='individual' $filter_qry");
	}
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}
	$getKycLists = $wpdb->get_results("SELECT * FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) AND `account_type`='individual' $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
	
	
	$rows = array();
	if( $getKycLists ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getKycLists as $getKycList ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'email'			=>	__('email', CIP_TXTDOMAIN),
				'firstname'	=>	__('firstname', CIP_TXTDOMAIN),
				'lastname'	=>	__('lastname', CIP_TXTDOMAIN),
				'dob'	=>	__('dob', CIP_TXTDOMAIN),
				'_date'	=>	__('_date', CIP_TXTDOMAIN),
				'lastupdate'	=>	__('lastupdate', CIP_TXTDOMAIN),
				'status'		=>	__('status', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getKycList->$columnKey;
					if( $columnKey == '_date' || $columnKey == 'lastupdate' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'dob' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'd/m/Y', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'status' ){
						switch ($columnsDataVal) {
							case 'pending':
								$columnsDataVal = __('Pending', CIP_TXTDOMAIN);
								break;
							case 'reject':
								$columnsDataVal = __('Rejected', CIP_TXTDOMAIN);
								break;
							case 'dropped':
								$columnsDataVal = __('Dropped', CIP_TXTDOMAIN);
								break;
							case 'approved':
								$columnsDataVal = __('Approved', CIP_TXTDOMAIN);
								break;
							default:
								$columnsDataVal = '—';
								break;
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$encryptId = base64_encode($getKycList->id . md5('CIP_kyc_CIP'));
			$viewUrl = add_query_arg( array('view' => $encryptId ), get_the_permalink( $_REQUEST['pageid'] ) );
			$row['action'] = '<a href="'.$viewUrl.'" class=""><i class="fas fa-eye"></i></a>';
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		// 'test'	=>	"SELECT * FROM $tableKyc WHERE 1 AND ( `status` <> '' AND `status` IS NOT NULL ) $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset"
	);
	echo wp_json_encode( $out );
	exit;
}
//5753
add_action('wp_ajax_csr_withdraw_requests_loader','cip_csr_withdraw_requests_loader_cb');
function cip_csr_withdraw_requests_loader_cb(){
	global $wpdb;
	$tableWithdraw = $wpdb->prefix.'withdraw_data_pending';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 500;
	$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 = "";
	$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['columnfilter'] ), 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 . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdraw WHERE 1 $filter_qry");
	}

	/* if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d %m %Y')";
	} */

	$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableWithdraw WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getWithdrawList ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getWithdrawList as $getWithdraw ){
			$row = array();
			$row['id'] = $sno;
			if( $isSelectAll == 1 ){
				$currentSelected = 1;
			}else if( $isSelectAll == 0 ){
				$currentSelected = 0;
			}
			$columnsArr = array(
				'token'							=>	__('Token', CIP_TXTDOMAIN),
				'withdrawal_process_status'		=>	__('withdrawal_process_status', CIP_TXTDOMAIN),
				'withdrawal_id'					=>	__('withdrawal_id', CIP_TXTDOMAIN),
				'email'							=>	__('email', CIP_TXTDOMAIN),
				'username'						=>	__('username', CIP_TXTDOMAIN),
				'first_name'					=>	__('first_name', CIP_TXTDOMAIN),
				'last_name'						=>	__('last_name', CIP_TXTDOMAIN),
				'user_star'						=>	__('user_star', CIP_TXTDOMAIN),
				'eth_address'					=>	__('eth_address', CIP_TXTDOMAIN),
				'withdraw_amount'				=>	__('withdraw_amount', CIP_TXTDOMAIN),
				'withdrawal_fee'				=>	__('withdrawal_fee', CIP_TXTDOMAIN),
				'received_amount'				=>	__('received_amount', CIP_TXTDOMAIN),
				'requested_date'				=>	__('requested_date', CIP_TXTDOMAIN),
			);
			$rowEncryptId = base64_encode( $getWithdraw->id . md5('CIP_WDREQUESTSELECTION_PIC'));
			$sessionSelectionData = ( isset( $_SESSION['sessionWdRequestSelectionData'] ) && !empty( $_SESSION['sessionWdRequestSelectionData'] ) ) ? $_SESSION['sessionWdRequestSelectionData'] : array();
			if( $isSelectAll == 1 && in_array( $rowEncryptId, $sessionSelectionData ) ){
				$currentSelected = 0;
			}else if( $isSelectAll == 0 && !in_array( $rowEncryptId, $sessionSelectionData ) ){
				$currentSelected = 1;
			}
			$row['rowiddata'] = '<input type="checkbox" name="rowiddata" class="rowiddata" data-withdrawalstatus="'.$getWithdraw->withdrawal_process_status.'" data-receivedamount="'. $getWithdraw->received_amount .'" data-token="'. $getWithdraw->token .'" value="'.$rowEncryptId.'" '.checked( $isSelectAll, $currentSelected, false ).' />';
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					if( $columnKey == 'withdrawal_id' ){
						$columnsDataVal = $getWithdraw->withdrawal_id;
					}else if( $columnKey == 'withdraw_amount' || $columnKey == 'withdrawal_fee' || $columnKey == 'received_amount' ){
						$columnsDataVal = number_format( $getWithdraw->$columnKey, 2 );
					}else if( $columnKey == 'eth_address' ){
						$columnsDataVal = '<a href="javascript:void(0);">'.$getWithdraw->$columnKey.'</a>';
					}else if( $columnKey == 'withdrawal_process_status' ){
						$columnsDataVal = __('Pending', CIP_TXTDOMAIN);
						if( $getWithdraw->withdrawal_process_status == 'Under review' ){
							$columnsDataVal = __('Under review', CIP_TXTDOMAIN);
						}
					}else{
						$columnsDataVal = $getWithdraw->$columnKey;
					}
					if( $columnKey == 'requested_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'user_star' ){
						if( empty( $columnsDataVal ) || $columnsDataVal <= 0 ){
							$columnsDataVal = 0;
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$encryptId = base64_encode($getWithdraw->id . md5('CIP_WithdrawalRequestCancel_CIP'));
			$data_micro = wp_create_nonce( $getWithdraw->id . md5('CIP_WithdrawalRequestCancel_CIP') );

			$encryptIdApprove = base64_encode($getWithdraw->id . md5('CIP_WithdrawalRequestApprove_CIP'));
			$data_micro_approve = wp_create_nonce( $getWithdraw->id . md5('CIP_WithdrawalRequestApprove_CIP') );

			$encryptIdReview = base64_encode($getWithdraw->id . md5('CIP_WithdrawalRequestReview_CIP'));
			$data_micro_review = wp_create_nonce( $getWithdraw->id . md5('CIP_WithdrawalRequestReview_CIP') );

			$approve_withdraw_btn = "";
			$review_withdraw_btn = "";
			if( $getWithdraw->withdrawal_process_status == 'Under review' ){
				$approve_withdraw_btn = '<a href="javascript:void(0);" class="approve_withdraw_request" data-approve="'. $encryptIdApprove .'" data-micro="'.$data_micro_approve.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Approve', CIP_TXTDOMAIN).'"><i class="fas fa-check"></i></a>';
			}else{
				$review_withdraw_btn = '<a href="javascript:void(0);" class="review_withdraw_request" data-review="'. $encryptIdReview .'" data-micro="'.$data_micro_review.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Review', CIP_TXTDOMAIN).'"><i class="fas fa-clock"></i></a>';
			}

			$row['action'] = '<div class="d-flex align-items-center" style="column-gap: 15px;"><a href="javascript:void(0);" class="cancel_withdraw_request" data-cancel="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Cancel', CIP_TXTDOMAIN).'"><i class="fas fa-trash-alt"></i></a> '. $approve_withdraw_btn . $review_withdraw_btn .' </div>';
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_tokenholder_wallet_delivery_loader','cip_tokenholder_wallet_delivery_loader_cb');
function cip_tokenholder_wallet_delivery_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();

	$whereStatus = "AND `corp_approved` IN('Pending','Partially Delivered')";

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $whereStatus ORDER BY `id` DESC");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 500;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'text_2';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$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;
		}
	}

	$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['columnfilter'] ), 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;
	}
	if( !empty( $filters ) ){
		$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');
		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 $tableName WHERE 1 $whereStatus $filter_qry ORDER BY `id` DESC");
	}
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $whereStatus $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");


	$saUserData = get_user_by( 'id', $user_id );
	global $defaultColumnsArr;
	if( $saUserData && ( in_array( "supportagent", $saUserData->roles ) || in_array( "supportmanager", $saUserData->roles ) ) ){
		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsSAColumnOption = (array)get_option('cip_column_sa_toggle_columns');
		$columnsSAToggleArr = (array)get_user_meta( $user_id, 'cip_sagent_toggle_columns', true );
		$columnsArr = array();
		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
			foreach( $columnOrders as $columnOrder ){
				if( isset( $columnsSAToggleArr[$columnOrder] ) ){
					$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
				}
			}
			if( empty( $columnsArr ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsSAColumnOption[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}else{
			unset( $defaultColumnsArr['imported_by'] );
			unset( $defaultColumnsArr['import_at'] );
			unset( $defaultColumnsArr['last_update_at'] );
			$columnsArr = $defaultColumnsArr;
		}
	}else{
		unset( $defaultColumnsArr['imported_by'] );
		unset( $defaultColumnsArr['import_at'] );
		unset( $defaultColumnsArr['last_update_at'] );
		$columnsArr = $defaultColumnsArr;
	}
	$total_amount_due = 0;
	$getAmountDue = $wpdb->get_row("SELECT SUM(`amount_due`) as `total_amount_due` FROM $tableName WHERE 1 $whereStatus $filter_qry");
	if( $getAmountDue ){
		$total_amount_due = $getAmountDue->total_amount_due;
	}

	$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) .')';
	}
	$total_selected_amount_due = 0;
	if( $isSelectAll != 0 || !empty( $sessionSelectionData ) ){
		$getSelectedAmountDue = $wpdb->get_row("SELECT SUM(`amount_due`) as `total_selected_amount_due` FROM $tableName WHERE 1 $whereStatus $filter_qry $sessionDataQry");
		if( $getSelectedAmountDue ){
			$total_selected_amount_due = $getSelectedAmountDue->total_selected_amount_due;
		}
	}

	$rows = array();
	$partialDeliverIds = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;

			if( $isSelectAll == 1 ){
				$currentSelected = 1;
			}else if( $isSelectAll == 0 ){
				$currentSelected = 0;
			}
			$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_WDSELECTION_PIC') );
			$partialDeliverIds[] = $rowEncryptId;
			// $decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			//$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);

			$sessionSelectionData = ( isset( $_SESSION['sessionSelectionData'] ) && !empty( $_SESSION['sessionSelectionData'] ) ) ? $_SESSION['sessionSelectionData'] : array();
			if( $isSelectAll == 1 && in_array( $rowEncryptId, $sessionSelectionData ) ){
				$currentSelected = 0;
			}else if( $isSelectAll == 0 && !in_array( $rowEncryptId, $sessionSelectionData ) ){
				$currentSelected = 1;
			}

			$row['rowiddata'] = '<input type="checkbox" name="rowiddata" class="rowiddata" data-amountdue="'. $getCurrentMember->amount_due .'" value="'.$rowEncryptId.'" '.checked( $isSelectAll, $currentSelected, false ).' />';
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
						$columnsDataVal = cip_trim_notes( $columnsDataVal );
						$columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '<a href="javascript:void(0);" class="modelpop_notes" data-toggle="modal" data-target="#viewMoreModal" data-id="'.$getCurrentMember->id.'" data-viewmore="'.wpautop( $columnsDataVal ).'" data-toggle-tt1="tooltip" data-placement1="top" title="'.$columnsDataVal150.'" ><img src="'.CIP_PLUGIN_FOLDER.'/images/view-more.png" class="view-more-notes" /></a>' );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}
					if( $columnKey == 'position' ){
						$positionVal = '—';
						$positionText = __('Distribution Position not set... Try back later',CIP_TXTDOMAIN);
						if( $columnsDataVal ){
							$positionVal = $columnsDataVal;
							$positionText = sprintf( __('Distribution Position is set... congratulations you are at position %s in the distribution list',CIP_TXTDOMAIN), $columnsDataVal );
						}
						$columnsDataVal = '<a href="javascript:void(0);" data-id="'.$getCurrentMember->id.'" data-toggle-tt="tooltip" data-placement="top" title="'.$positionText.'" >'.$positionVal.'</a>';
					}
					if($columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' || $columnKey == 'saved_amount'){
						$row[$columnKey] =  cip_number_format($columnsDataVal,false);
					}else{
						$row[$columnKey] = $columnsDataVal;
					}
				}
			}

			// $row['action'] = '<a href="'.$editLink.'" title="edit"><i class="fas fa-edit"></i></a>'.$unVerifyLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$partialDeliverIdsString = "";
	if( count( $partialDeliverIds ) <= 15 && count( $partialDeliverIds ) > 0 ){
		$partialDeliverIdsString = implode(',', $partialDeliverIds);
	}

	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		'total_amount_due'	=>	number_format( $total_amount_due ),
		'total_selected_amount_due'	=>	number_format( $total_selected_amount_due ),
		'partialDeliverIds'	=>	$partialDeliverIdsString,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_tokenholder_wallet_delivery_report_loader','cip_tokenholder_wallet_delivery_report_loader_cb');
function cip_tokenholder_wallet_delivery_report_loader_cb(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$user_id = get_current_user_id();
	// $note89Where = "AND ( `note_8` IS NOT NULL AND `note_8` <> '') AND ( `note_9` IS NOT NULL AND `note_9` <> '')";
	$note89Where = "AND ( `note_8` IS NOT NULL AND `note_8` <> '')";
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $note89Where ORDER BY `id` DESC");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 20;
	$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 = "";
	$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['columnfilter'] ), 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;
	}
	if( !empty( $filters ) ){
		$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');
		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 == 'note_8' || $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $note89Where $filter_qry ORDER BY `id` DESC");
	}
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $note89Where $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");


	$saUserData = get_user_by( 'id', $user_id );
	global $defaultColumnsArr;
	if( $saUserData && ( in_array( "supportagent", $saUserData->roles ) || in_array( "supportmanager", $saUserData->roles ) ) ){
		$columnOrders = (array)get_option('cip_sm_column_order');
		$columnsLabelArr = (array)get_option('cip_sm_column_labels');
		$columnsSAColumnOption = (array)get_option('cip_column_sa_toggle_columns');
		$columnsSAToggleArr = (array)get_user_meta( $user_id, 'cip_sagent_toggle_columns', true );
		$columnsArr = array();
		if( !empty( $columnOrders ) && is_array( $columnOrders ) ){
			foreach( $columnOrders as $columnOrder ){
				if( isset( $columnsSAToggleArr[$columnOrder] ) ){
					$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
				}
			}
			if( empty( $columnsArr ) ){
				foreach( $columnOrders as $columnOrder ){
					if( isset( $columnsSAColumnOption[$columnOrder] ) ){
						$columnsArr[$columnOrder] = ( isset( $columnsLabelArr[$columnOrder] ) && !empty( $columnsLabelArr[$columnOrder] ) ) ? $columnsLabelArr[$columnOrder] : $defaultColumnsArr[$columnOrder];
					}
				}
			}
		}else{
			unset( $defaultColumnsArr['imported_by'] );
			unset( $defaultColumnsArr['import_at'] );
			unset( $defaultColumnsArr['last_update_at'] );
			$columnsArr = $defaultColumnsArr;
		}
	}else{
		unset( $defaultColumnsArr['imported_by'] );
		unset( $defaultColumnsArr['import_at'] );
		unset( $defaultColumnsArr['last_update_at'] );
		$columnsArr = $defaultColumnsArr;
	}
	$columnsArrNew['note_8'] = __('Delivery Batch Id', CIP_TXTDOMAIN);
	// $columnsArrNew['note_9'] = __('Delivery Reference Id', CIP_TXTDOMAIN);
	$columnsArr = $columnsArrNew + $columnsArr;
	$total_amount_due = 0;
	$getAmountDue = $wpdb->get_row("SELECT SUM(`amount_due`) as `total_amount_due` FROM $tableName WHERE 1 $filter_qry");
	if( $getAmountDue ){
		$total_amount_due = $getAmountDue->total_amount_due;
	}
	$rows = array();
	$partialDeliverIds = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;
			$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_WDSELECTION_PIC'));
			$partialDeliverIds[] = $rowEncryptId;
			// $decryptedIdRaw = base64_decode( $_POST['microtoken'] );
			//$decryptedUserId = preg_replace(sprintf('/%s/', md5('CIP_WDSELECTION_PIC') ), '', $decryptedIdRaw);

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCurrentMember->$columnKey;
					$verified = ( $getCurrentMember->sign_verify == 1 ) ? true : false;
					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>';
							if( $verified ){ $columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />'; }
						}else{
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
						$columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '<a href="javascript:void(0);" class="modelpop_notes" data-toggle="modal" data-target="#viewMoreModal" data-id="'.$getCurrentMember->id.'" data-viewmore="'.wpautop( $columnsDataVal ).'" data-toggle-tt1="tooltip" data-placement1="top" title="'.$columnsDataVal150.'" ><img src="'.CIP_PLUGIN_FOLDER.'/images/view-more.png" class="view-more-notes" /></a>' );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}
					if( $columnKey == 'position' ){
						$positionVal = '—';
						$positionText = __('Distribution Position not set... Try back later',CIP_TXTDOMAIN);
						if( $columnsDataVal ){
							$positionVal = $columnsDataVal;
							$positionText = sprintf( __('Distribution Position is set... congratulations you are at position %s in the distribution list',CIP_TXTDOMAIN), $columnsDataVal );
						}
						$columnsDataVal = '<a href="javascript:void(0);" data-id="'.$getCurrentMember->id.'" data-toggle-tt="tooltip" data-placement="top" title="'.$positionText.'" >'.$positionVal.'</a>';
					}
					if($columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' || $columnKey == 'saved_amount'){
						$row[$columnKey] = cip_number_format($columnsDataVal,false);
					}else{
						$row[$columnKey] = $columnsDataVal;
					}
				}
			}

			// $row['action'] = '<a href="'.$editLink.'" title="edit"><i class="fas fa-edit"></i></a>'.$unVerifyLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$partialDeliverIdsString = "";
	if( count( $partialDeliverIds ) <= 15 && count( $partialDeliverIds ) > 0 ){
		$partialDeliverIdsString = implode(',', $partialDeliverIds);
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		'total_amount_due'	=>	number_format( $total_amount_due ),
		// 'partialDeliverIds'	=>	$partialDeliverIdsString,
		// 'test_query' => "SELECT * FROM $tableName WHERE 1 $note89Where $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset",
	);
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_downloadingCsrWDeliveryReport', 'downloadingCsrWDeliveryReport_callback' );
function downloadingCsrWDeliveryReport_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_XyCheckCSRWalletDeliveryReportDownloadyX_' ) && ( current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' ) ) ){
		// $note89Where = "AND ( `note_8` IS NOT NULL AND `note_8` <> '') AND ( `note_9` IS NOT NULL AND `note_9` <> '')";
		$note89Where = "AND ( `note_8` IS NOT NULL AND `note_8` <> '')";
		$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';

		$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 $note89Where 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 == 'note_8' ){
					$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
				}else{
					$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
				}
			}
			$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTokenHolder WHERE 1 $note89Where $filter_qry AND `amount_due` > 0 $sessionDataQry");
		}
		$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableTokenHolder WHERE 1 $note89Where $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);
			}
		}
		fseek($exportFile, 0);
		$file_name = 'Wallet-Delivery-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;
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_csr_transaction_history_deposit_loader','cip_csr_transaction_history_deposit_loader_cb');
function cip_csr_transaction_history_deposit_loader_cb(){
	global $wpdb;
	$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTransactionHistory WHERE 1 AND `type`='deposit' AND $whereEmail");

	$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 ){
			if( $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == '_date' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$filterData'";
				}
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTransactionHistory WHERE 1 AND `type`='deposit' AND $whereEmail $filter_qry");
	}
	/* $isDateColumn = array('_date');
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	} */

	$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableTransactionHistory WHERE 1 AND `type`='deposit' AND $whereEmail $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getWithdrawList ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getWithdrawList as $getWithdraw ){
			$row = array();
			// $row['id'] = $sno;
			$columnsArr = array(
				// 'id'				=>	__('id', CIP_TXTDOMAIN),
				'txn_id'			=>	__('txn_id', CIP_TXTDOMAIN),
				'withdrawal_amount'	=>	__('withdrawal_amount', CIP_TXTDOMAIN),
				'withdrawal_fee'	=>	__('withdrawal_fee', CIP_TXTDOMAIN),
				'received_amount'	=>	__('received_amount', CIP_TXTDOMAIN),
				'type'				=>	__('type', CIP_TXTDOMAIN),
				'_date'				=>	__('_date', CIP_TXTDOMAIN),
				'short_description'	=>	__('short_description', CIP_TXTDOMAIN),
				'status'			=>	__('status', CIP_TXTDOMAIN),
				'token'				=>	__('Token', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					if( $columnKey == 'withdrawal_id' ){
						$columnsDataVal = $getWithdraw->id;
					}else if( $columnKey == 'withdrawal_amount' || $columnKey == 'withdrawal_fee' || $columnKey == 'received_amount' ){
						$columnsDataVal = number_format( $getWithdraw->$columnKey, 2 );
					}else if( $columnKey == 'eth_address' ){
						$columnsDataVal = '<a href="javascript:void(0);">'.$getWithdraw->$columnKey.'</a>';
					}else if( $columnKey == 'short_description' ){
						$columnsDataVal = $getWithdraw->$columnKey;
						// $columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '.... ' . cipColumnHeaderTooltip( $getWithdraw->short_description ) );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}else if( $columnKey == 'type' ){
						$columnsDataVal = ucfirst( $getWithdraw->$columnKey );
					}else{
						$columnsDataVal = $getWithdraw->$columnKey;
					}
					if( $getWithdraw->type == 'withdrawal' ){
						if( $columnKey == 'withdrawal_amount' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
						if( $columnKey == 'withdrawal_fee' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
						if( $columnKey == 'received_amount' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
					}else if( $getWithdraw->type == 'deposit' ){
						if( $columnKey == 'received_amount' ){
							$columnsDataVal = '+'.$columnsDataVal;
						}
						if( $columnKey == 'withdrawal_amount' || $columnKey == 'withdrawal_fee' ){
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == '_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('Y-m-d H:i') . ' GMT';
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$status = '—';
					if( $columnKey == 'status' ){
						$columnsDataVal = $status;
						if( $getWithdraw->type == 'deposit' ){
							if( $getWithdraw->status == 0 ){
								$status = __('Completed', CIP_TXTDOMAIN);
							}else if( $getWithdraw->status == -1 ){
								$status = __('Cancelled', CIP_TXTDOMAIN) . ' ' . cipColumnHeaderTooltip( $getWithdraw->reason );
							}
							$columnsDataVal = $status;
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_csr_transaction_history_withdrawals_loader','cip_csr_transaction_history_withdrawals_loader_cb');
function cip_csr_transaction_history_withdrawals_loader_cb(){
	global $wpdb;
	$tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';
	$tableWithdrawDataPending = $wpdb->prefix.'withdraw_data_pending';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';
	$whereEmail = "`email` = '".$refAccount."' AND `email` IS NOT NULL AND `email` != ''";
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTransactionHistory WHERE 1 AND `type`='withdrawal' AND $whereEmail");

	$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 ){
			if( $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == '_date' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$filterData'";
				}
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableTransactionHistory WHERE 1 AND `type`='withdrawal' AND $whereEmail $filter_qry");
	}
	/* $isDateColumn = array('_date');
	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE(`$orderby`,'%d/%m/%Y')";
	} */

	$getWithdrawList = $wpdb->get_results("SELECT * FROM $tableTransactionHistory WHERE 1 AND `type`='withdrawal' AND $whereEmail $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';
	$rows = array();
	if( $getWithdrawList ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getWithdrawList as $getWithdraw ){
			$row = array();
			// $row['id'] = $sno;
			$columnsArr = array(
				// 'id'				=>	__('id', CIP_TXTDOMAIN),
				'txn_id'			=>	__('txn_id', CIP_TXTDOMAIN),
				'withdrawal_amount'	=>	__('withdrawal_amount', CIP_TXTDOMAIN),
				'withdrawal_fee'	=>	__('withdrawal_fee', CIP_TXTDOMAIN),
				'received_amount'	=>	__('received_amount', CIP_TXTDOMAIN),
				'eth_address'		=>	__('eth_address', CIP_TXTDOMAIN),
				'transhash'			=>	__('transhash', CIP_TXTDOMAIN),
				'type'				=>	__('type', CIP_TXTDOMAIN),
				'_date'				=>	__('_date', CIP_TXTDOMAIN),
				'short_description'	=>	__('short_description', CIP_TXTDOMAIN),
				'status'			=>	__('status', CIP_TXTDOMAIN),
				'token'				=>	__('Token', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){

					$getPendingWithdrawalStatus = $wpdb->get_row("SELECT * FROM $tableWithdrawDataPending WHERE `withdrawal_id` = '". $getWithdraw->txn_id ."' ORDER BY `id` DESC LIMIT 1");

					if( $columnKey == 'withdrawal_id' ){
						$columnsDataVal = $getWithdraw->id;
					}else if( $columnKey == 'withdrawal_amount' || $columnKey == 'withdrawal_fee' || $columnKey == 'received_amount' ){
						$columnsDataVal = number_format( $getWithdraw->$columnKey, 2 );
					}else if( $columnKey == 'eth_address' ){
						$columnsDataVal = $getWithdraw->$columnKey;
						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 = '—';
						}
						// $columnsDataVal = '<a href="javascript:void(0);">'.$getWithdraw->$columnKey.'</a>';
					}else if( $columnKey == 'transhash'){
						$columnsDataVal = $getWithdraw->$columnKey;
						if( !empty( $columnsDataVal ) ){
							$columnsDataValMask = substr($columnsDataVal, 0, 4) . '...' . substr($columnsDataVal, -4);
							$columnsDataVal = '<a href="'. $endpoint . $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.__('Your CSR Withdrawals was processed in the batch with transaction Hash', CIP_TXTDOMAIN).'" >'. $columnsDataValMask . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'short_description' ){
						$columnsDataVal = $getWithdraw->$columnKey;
						$short_description = $getWithdraw->short_description;
						if( $getPendingWithdrawalStatus && $getPendingWithdrawalStatus->withdrawal_process_status == 'Under review' ){
							$columnsDataVal = __('Withdrawal under review by the management.', CIP_TXTDOMAIN);
							$short_description = $columnsDataVal;
						}else if( $getWithdraw->type == 'withdrawal' && $getWithdraw->status == 0 ){
							$short_description = __('CSR withdrawal request to blockchain', CIP_TXTDOMAIN);
							$columnsDataVal = __('CSR withdrawal request to blockchain', CIP_TXTDOMAIN);
						}

						// $columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '.... ' . cipColumnHeaderTooltip( $short_description ) );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}else if( $columnKey == 'type' ){
						$columnsDataVal = ucfirst( $getWithdraw->$columnKey );
					}else{
						$columnsDataVal = $getWithdraw->$columnKey;
					}


					if( $getWithdraw->type == 'withdrawal' ){
						if( $columnKey == 'withdrawal_amount' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
						if( $columnKey == 'withdrawal_fee' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
						if( $columnKey == 'received_amount' ){
							$columnsDataVal = '-'.$columnsDataVal;
						}
					}else if( $getWithdraw->type == 'deposit' ){
						if( $columnKey == 'received_amount' ){
							$columnsDataVal = '+'.$columnsDataVal;
						}
						if( $columnKey == 'withdrawal_amount' || $columnKey == 'withdrawal_fee' ){
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == '_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('Y-m-d H:i') . ' GMT';
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$status = __('-', CIP_TXTDOMAIN);
					if( $columnKey == 'status' ){
						$columnsDataVal = $status;
						if( $getWithdraw->type == 'withdrawal' ){
							if( $getWithdraw->status == 0 ){
								$status = __('Pending', CIP_TXTDOMAIN);
							}else if( $getWithdraw->status == 1 ){
								$status = __('In Process', CIP_TXTDOMAIN);
							}else if( $getWithdraw->status == 2 ){
								$status = __('Completed', CIP_TXTDOMAIN);
							}else if( $getWithdraw->status == -1 ){
								$status = __('Cancelled', CIP_TXTDOMAIN) . ' ' . cipColumnHeaderTooltip( $getWithdraw->reason );
							}

							if( $getPendingWithdrawalStatus && $getPendingWithdrawalStatus->withdrawal_process_status == 'Under review' ){
								$status = $getPendingWithdrawalStatus->withdrawal_process_status;
							}

							$columnsDataVal = $status;
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}

			$encryptId = base64_encode($getWithdraw->id . md5('CIP_UserWithdrawalRequestCancel_CIP'));
			$data_micro = wp_create_nonce( $getWithdraw->id . md5('CIP_UserWithdrawalRequestCancel_CIP') );
			$cancelBtn = '&mdash;';
			if( $getWithdraw->type == 'withdrawal' && $getWithdraw->status == 0 ){
				$cancelBtn = '<a href="javascript:void(0);" class="user_cancel_pending_withdraw_request" data-cancel="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Cancel', CIP_TXTDOMAIN).'"><i class="fas fa-trash-alt"></i></a>';
			}
			$row['action'] = $cancelBtn;

			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_supportagent_users_list_loader','cip_supportagent_users_list_loader_cb');
function cip_supportagent_users_list_loader_cb(){
	global $wpdb;

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'login';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	$args = array(
		'role' 		=> 'supportagent',
		'fields' 	=> 'ID',
		'number' 	=> $limit,
		'offset' 	=> $offset,
		'orderby'	=> $orderby,
		'order'		=> $order,
	);
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'email' ){
				$args = wp_parse_args( ['search' => "*{$filterData}*", 'search_columns' => ['user_login', 'user_email'] ], $args );
			}
		}
	}
	$memberQuery = new WP_User_Query( $args );
	$memberData = $memberQuery->get_results();
	$total_items = $memberQuery->get_total();
	$rows = array();
	if( !empty( $memberData ) ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $memberData as $user_id ){
			$memberInfo = get_userdata($user_id);
			if( $memberInfo ){
				$google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );

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

				$row['email'] = $memberInfo->user_email;
				$encryptId = base64_encode( $user_id . md5('324CL_SupportagenT_CL324'));
				if( !empty( $google_auth_key ) ){
					$row['action_g2fa'] = '<a href="javascript:void(0);" class="disableSA2faauth" data-toggle-tt="tooltip" data-placement="top" data-pop-title="disable google 2FA" title="'.__('Disable', 'corsair-login').'" data-id="'.$encryptId.'" data-type="'.base64_encode( md5('Google2FAReset') ).'"><i class="fas fa-undo"></i></a></a>';
				}else{
					$row['action_g2fa'] = '-';
				}
				$rows[] = $row;
				$sno=$sno+1;
			}
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'args'			=>	$args,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_completed_withdrawals_list_loader','cip_completed_withdrawals_list_loader');
function cip_completed_withdrawals_list_loader(){
	global $wpdb;
	$tableWithdrawalRequestsCsv = $wpdb->prefix.'withdrawal_requests_csv';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalRequestsCsv WHERE `status`=1");

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

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	$isNumericColumn = array( 'total_withdrawals', 'total_withdrawals_amount' );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'last_update' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$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($filterKey == 'token'){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalRequestsCsv WHERE `status`=1 $filter_qry");
	}
	$getRequestCsvs = $wpdb->get_results("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `status`=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';

	$rows = array();
	if( $getRequestCsvs ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getRequestCsvs as $getRequestCsv ){
			$row = array();
			// $row['id'] = $sno;
			$columnsArr = array(
				// 'fileid'					=>	__('fileid', CIP_TXTDOMAIN),
				'token'						=>	__('token', CIP_TXTDOMAIN),
				'withdrawal_batch_id'		=>	__('withdrawal_batch_id', CIP_TXTDOMAIN),
				'total_withdrawals'			=>	__('total_withdrawals', CIP_TXTDOMAIN),
				// 'total_withdrawals_amount'	=>	__('total_withdrawals_amount', CIP_TXTDOMAIN),
				'total_withdrawals_amount_fees'	=>	__('total_withdrawals_amount_fees', CIP_TXTDOMAIN),
				'last_update'				=>	__('last_update', CIP_TXTDOMAIN),
				'transhash'					=>	__('transhash', CIP_TXTDOMAIN),
				'status'					=>	__('status', CIP_TXTDOMAIN),
				'download'					=>	__('download', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					if( $columnKey == 'status' ){
						$columnsDataVal = __('Completed', CIP_TXTDOMAIN);
					}else if( $columnKey == 'total_withdrawals' ){
						$columnsDataVal = number_format( $getRequestCsv->$columnKey );
					}else if( $columnKey == 'total_withdrawals_amount' ){
						$columnsDataVal = number_format( $getRequestCsv->$columnKey, 2 );
					}else if( $columnKey == 'total_withdrawals_amount_fees' ){
						$columnsDataVal = number_format( $getRequestCsv->$columnKey, 2 );
					}else if( $columnKey == 'transhash'){
						$columnsDataVal = $getRequestCsv->$columnKey;
						if( !empty( $columnsDataVal ) ){
							$columnsDataValMask = substr($columnsDataVal, 0, 4) . '...' . substr($columnsDataVal, -4);
							$columnsDataVal = '<a href="'. $endpoint . $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataValMask . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'download' ){
						$encryptId = base64_encode( $getRequestCsv->fileid . md5('CIPWithdrawalRequestCSV'));
						$wizardExportUrl = add_query_arg( array(
							'action'	=> 'completed_withdrawal_request_csv_download_act',
							'_micro'	=> wp_create_nonce('_CIP_COMPLETED_WITHDRAWAL_REQUEST_DOWNLOAD_CSV_CIP_'),
							'file'		=> $encryptId,
							'completed'	=> 1,
						), admin_url('admin-post.php') );
						$wizardExportViewUrl = add_query_arg( array(
							'action'	=> 'withdrawal_request_view_act',
							'_micro'	=> wp_create_nonce('_CIP_COMPLETED_WITHDRAWAL_REQUEST_VIEW_CIP_'),
							'file'		=> $encryptId,
							'completed'	=> 1,
						), get_permalink( $_REQUEST['pageid'] ) );
						$columnsDataVal = '<div class="d-flex justify-content-center" style="column-gap:10px;"><a href="'. $wizardExportUrl .'" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.__('Download', CIP_TXTDOMAIN).'"><i class="fa fa-file-download"></i></a><a href="'. $wizardExportViewUrl .'" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.__('View', CIP_TXTDOMAIN).'"><i class="fa fa-eye"></i></a></div>';
					}else{
						$columnsDataVal = $getRequestCsv->$columnKey;
					}
					if( $columnKey == 'last_update' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y H:i');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						if( empty( $columnsDataVal ) ){
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_completed_withdrawals_list_export','cip_completed_withdrawals_list_export_cb');
function cip_completed_withdrawals_list_export_cb(){
	global $wpdb;
	$tableWithdrawalRequestsCsv = $wpdb->prefix.'withdrawal_requests_csv';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalRequestsCsv WHERE `status`=1");

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

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	$isNumericColumn = array( 'total_withdrawals', 'total_withdrawals_amount' );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'last_update' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$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($filterKey == 'token'){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalRequestsCsv WHERE `status`=1 $filter_qry");
	}
	$getRequestCsvs = $wpdb->get_results("SELECT * FROM $tableWithdrawalRequestsCsv WHERE `status`=1 $filter_qry ORDER BY `$orderby` $order");

	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';

	if (empty($getRequestCsvs)) {
        wp_die(__('No data available for export.', 'your-text-domain'));
    }

    $fileName = 'Completed withdrawals '.date("Ymd").'.csv';

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="'.$fileName.'"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $output = fopen('php://output', 'w');
    $columns = array('Withdrawal Batch Id', 'Total Withdrawals', 'Amount of CSR', 'Transaction hash', 'Date time (GMT)', 'Status');
    fputcsv($output, $columns);

    foreach ($getRequestCsvs as $row) {

    	$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $row->last_update );
		$last_update = $user_date_obj->format('d-m-Y H:i');

        fputcsv($output, array(
            $row->withdrawal_batch_id,
            number_format($row->total_withdrawals),
            number_format($row->total_withdrawals_amount_fees),
            $row->transhash,
            $last_update,
            'Completed',
        ));
    }

    fclose($output);

    exit;

}
add_action('wp_ajax_cip_completed_withdrawals_all_list_loader','cip_completed_withdrawals_all_list_loader');
function cip_completed_withdrawals_all_list_loader(){
	global $wpdb;
	$tableWithdrawComplete = $wpdb->prefix.'withdraw_data_completed';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawComplete WHERE 1");

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

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	$isNumericColumn = array( 'withdraw_amount', 'withdrawal_fee', 'received_amount' );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'processed_date' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$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( $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == 'withdrawal_batch_id' ){
				$filter_qry .= " AND `$filterKey` = " . $filterData . "";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawComplete WHERE 1 $filter_qry");
	}

	$getRequestCsvs = $wpdb->get_results("SELECT * FROM $tableWithdrawComplete WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/address/' : 'https://sepolia.etherscan.io/address/';
	$endpointTxn = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';

	$rows = array();
	if( $getRequestCsvs ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getRequestCsvs as $getRequestCsv ){
			$row = array();
			// $row['id'] = $sno;
			$columnsArr = array(
				'token'					=>  __('token', CIP_TXTDOMAIN),
				'withdrawal_batch_id'	=>	__('withdrawal_batch_id', CIP_TXTDOMAIN),
				'withdrawal_id'			=>	__('withdrawal_id', CIP_TXTDOMAIN),
				'username'				=>	__('username', CIP_TXTDOMAIN),
				'email'					=>	__('email', CIP_TXTDOMAIN),
				'eth_address'			=>	__('eth_address', CIP_TXTDOMAIN),
				'transhash'				=>	__('transhash', CIP_TXTDOMAIN),
				'withdraw_amount'		=>	__('withdraw_amount', CIP_TXTDOMAIN),
				'withdrawal_fee'		=>	__('withdrawal_fee', CIP_TXTDOMAIN),
				'received_amount'		=>	__('received_amount', CIP_TXTDOMAIN),
				'processed_date'		=>	__('processed_date', CIP_TXTDOMAIN),
			);

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getRequestCsv->$columnKey;
					if( $columnKey == 'eth_address'){
						if( !empty( $columnsDataVal ) ){
							$columnsDataValMask = substr($columnsDataVal, 0, 6) . '...' . substr($columnsDataVal, -6);
							$columnsDataVal = '<a href="'. $endpoint . $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataValMask . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'transhash'){
						if( !empty( $columnsDataVal ) ){
							$columnsDataValMask = substr($columnsDataVal, 0, 4) . '...' . substr($columnsDataVal, -4);
							$columnsDataVal = '<a href="'. $endpointTxn . $columnsDataVal . '#tokentxns" target="_blank" data-toggle-tt="tooltip" data-placement="top" title="'.$columnsDataVal.'" >'. $columnsDataValMask . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}else if( $columnKey == 'withdraw_amount' || $columnKey == 'withdrawal_fee' || $columnKey == 'received_amount' ){
						$columnsDataVal = number_format( $columnsDataVal, 2, '.', ',' );
					}else if( $columnKey == 'processed_date' ){
						try {
							$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $columnsDataVal );
							$columnsDataVal = $user_date_obj->format('d-m-Y H:i');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}else{
						$columnsDataVal = $getRequestCsv->$columnKey;
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		// 'test'			=>	"SELECT * FROM $tableWithdrawComplete WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset"
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_completed_withdrawals_all_list_export','cip_completed_withdrawals_all_list_export');
function cip_completed_withdrawals_all_list_export(){
	global $wpdb;
	$tableWithdrawComplete = $wpdb->prefix.'withdraw_data_completed';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawComplete WHERE 1");

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

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	$isNumericColumn = array( 'withdraw_amount', 'withdrawal_fee', 'received_amount' );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'processed_date' ){
				if( str_contains($filterData, ' - ') ){
					$filterDataMinMax = explode(' - ', $filterData);
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') BETWEEN '$filterDataMinMax[0]' AND '$filterDataMinMax[1]'";
				}else{
					$filter_qry .= " AND DATE_FORMAT(`$filterKey`,'%d-%m-%Y') = '$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( $filterKey == 'token' ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else if( $filterKey == 'withdrawal_batch_id' ){
				$filter_qry .= " AND `$filterKey` = " . $filterData . "";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawComplete WHERE 1 $filter_qry");
	}

	$getRequestCsvs = $wpdb->get_results("SELECT * FROM $tableWithdrawComplete WHERE 1 $filter_qry ORDER BY `$orderby` $order");
	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/address/' : 'https://sepolia.etherscan.io/address/';
	$endpointTxn = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';

	if (empty($getRequestCsvs)) {
        wp_die(__('No data available for export.', 'your-text-domain'));
    }

    $fileName = 'Completed withdrawals all '.date("Ymd").'.csv';

    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="'.$fileName.'"');
    header('Pragma: no-cache');
    header('Expires: 0');

    $output = fopen('php://output', 'w');
    $columns = array('Token', 'Withdrawal Batch ID', 'Withdrawal ID', 'Username', 'Email', 'Wallet Address', 'Transaction hash', 'Withdrawal Amount', 'Withdrawal Fee', 'Received Amount', 'Date time (GMT)');
    fputcsv($output, $columns);

    foreach ($getRequestCsvs as $row) {

    	$user_date_obj = DateTime::createFromFormat( 'Y-m-d H:i:s', $row->processed_date );
		$processed_date = $user_date_obj->format('d-m-Y H:i');

        fputcsv($output, array(
            $row->token,
            $row->withdrawal_batch_id,
            $row->withdrawal_id,
            $row->username,
            $row->email,
            $row->eth_address,
            $row->transhash,
            number_format($row->withdraw_amount),
            number_format($row->withdrawal_fee),
            number_format($row->received_amount),
            $processed_date,
        ));
    }

    fclose($output);
    exit;
}
add_action('wp_ajax_cip_simple_notes_management_list_loader','cip_simple_notes_management_list_loader');
function cip_simple_notes_management_list_loader(){
	global $wpdb;
	$tableSimpleNotes = $wpdb->prefix.'simple_notes';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableSimpleNotes WHERE `status`=1");

	$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 ){
			$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableSimpleNotes WHERE `status`=1 $filter_qry");
	}

	$getSimpleNotes = $wpdb->get_results("SELECT * FROM $tableSimpleNotes WHERE `status`=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getSimpleNotes ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getSimpleNotes as $getSimpleNote ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'notes' =>	__('notes', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){

					$columnsDataVal = $getSimpleNote->$columnKey;
					$encryptId = base64_encode($getSimpleNote->id . md5('CIP_SimpleNotes_CIP'));
					$data_micro = wp_create_nonce( $getSimpleNote->id . md5('CIP_SimpleNotes_CIP') );
					$row['action'] = '<a href="javascript:void(0);" class="edit-simaple-notes ml-3" data-edit="'. $encryptId .'" data-micro="'.$data_micro.'"><i class="fas fa-pencil-alt"></i></a><a href="javascript:void(0);" class="delete-simaple-notes ml-3" data-delete="'. $encryptId .'" data-micro="'.$data_micro.'"><i class="fas fa-trash-alt"></i></a>';
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_sms_alert_management_list_loader','cip_sms_alert_management_list_loader');
function cip_sms_alert_management_list_loader(){
	global $wpdb;
	$tableSmsAlert = $wpdb->prefix.'sms_alert';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableSmsAlert WHERE `status`=1");

	$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 ){
			$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableSmsAlert WHERE `status`=1 $filter_qry");
	}

	$getSmsAlerts = $wpdb->get_results("SELECT * FROM $tableSmsAlert WHERE `status`=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getSmsAlerts ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getSmsAlerts as $getSmsAlert ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'number' =>	__('number', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){

					$columnsDataVal = $getSmsAlert->$columnKey;
					$encryptId = base64_encode($getSmsAlert->id . md5('CIP_SmsAlert_CIP'));
					$data_micro = wp_create_nonce( $getSmsAlert->id . md5('CIP_SmsAlert_CIP') );
					$row['action'] = '<!--a href="javascript:void(0);" class="edit-sms-alert ml-3" data-edit="'. $encryptId .'" data-micro="'.$data_micro.'"><i class="fas fa-pencil-alt"></i></a--><a href="javascript:void(0);" class="delete-sms-alert ml-3" data-delete="'. $encryptId .'" data-number="'.$getSmsAlert->number.'" data-micro="'.$data_micro.'"><i class="fas fa-trash-alt"></i></a>';
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_cip_amount_wallet_table_loader','cip_cip_amount_wallet_table_loader_cb');
function cip_cip_amount_wallet_table_loader_cb(){
	global $wpdb;
	$tableCsrSavings = $wpdb->prefix.'csr_savings';
	$refAccount = ( isset( $_SESSION['refAccount'] ) ) ? $_SESSION['refAccount'] : '-';

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

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 AND `email` = '".$refAccount."'");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 5;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : "`status`='matured' desc, `status`='active' desc, `status`='paid' desc, STR_TO_DATE(`saving_end_date`,'%d/%m/%Y')";
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$filter_qry = "";

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	$isNumericColumn = array('saving_periods', 'saving_interest', 'saved_amount');
    $isDateColumn = array('saving_start_date', 'saving_end_date');

	if( in_array( $orderby, $isDateColumn ) ){
		$orderby = "STR_TO_DATE($orderby,'%d/%m/%Y')";
	}

	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'saving_start_date' || $filterKey == 'saving_end_date' ){
				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( 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{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrSavings WHERE 1 AND `email` = '".$refAccount."' $filter_qry");
	}

	$getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableCsrSavings WHERE 1 AND `email` = '".$refAccount."' $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$rows = array();
	$accrued_interest_total = 0;
	$totalSavedAmount = 0;
	$totalSavedAmountInterest = 0;

	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){

			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'status'            =>  __('Status', CIP_TXTDOMAIN),
				'reference'         =>  __('Reference', CIP_TXTDOMAIN),
				'saved_amount'      =>  __('Amount', CIP_TXTDOMAIN),
				'accrued_interest'  =>  __('Accrued Interest', CIP_TXTDOMAIN),
				'interest_due'   	=>  __('Interest Due', CIP_TXTDOMAIN),
				'saving_interest'   =>  __('Saving Interest', CIP_TXTDOMAIN),
				'saving_periods'    =>  __('Duration', CIP_TXTDOMAIN),
				'saving_start_date' =>  __('Start Date', CIP_TXTDOMAIN),
				'saving_end_date' 	=>  __('Date of maturity', CIP_TXTDOMAIN),
			);

			$interest_amount = 0;
			$currentDaySaving = 0;
			$interest_amount_by_periods = 0;
			try{

				$startDateObj = DateTime::createFromFormat('d/m/Y', $getCurrentMember->saving_start_date);
				$currentDateObj = DateTime::createFromFormat( 'd/m/Y', date_i18n('d/m/Y') );

				$startDate = DateTime::createFromFormat( 'Y-m-d', $startDateObj->format('Y-m-d') );
				$currentDate = DateTime::createFromFormat( 'Y-m-d', $currentDateObj->format('Y-m-d') );

				$interval = $startDate->diff($currentDate);
				$intervalNumber = $interval->format('%R%a');

				if( $getCurrentMember->saved_amount > 0 && $getCurrentMember->saving_interest > 0 ){
					$interest_amount = round( $getCurrentMember->saved_amount * $getCurrentMember->saving_interest / 100 );
				}
				if( $getCurrentMember->saved_amount > 0 && $getCurrentMember->saving_interest > 0 ){
					$interest_amount_by_periods = ( $getCurrentMember->saved_amount * $getCurrentMember->saving_interest / 100 ) / $getCurrentMember->saving_periods;
				}
				$totalDaysCount = 0;
				$intInterval = (int)$interval->format('%a');
				// echo $intervalNumber;
				if( $intervalNumber >= 0 && $intInterval <= $getCurrentMember->saving_periods ){
					$totalDaysCount = $intInterval;
				}else if( $intervalNumber < 0 ){
					$totalDaysCount = 0;
				}else{
					$totalDaysCount = $getCurrentMember->saving_periods;
				}
				$currentDaySaving = round( $totalDaysCount * $interest_amount_by_periods );
			}catch(\Throwable $th){
				$interest_amount = 0;
				$currentDaySaving = 0;
			}

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

					$columnsDataVal = $getCurrentMember->$columnKey;

					if( in_array( $columnKey, $isNumericColumn ) ){
						$columnsDataVal = number_format( $columnsDataVal );
					}else if( $columnKey == 'status' ){
						$columnsDataVal = ucfirst( $columnsDataVal );
					}else if( $columnKey == 'interest_due' ){
						$columnsDataVal = number_format( $interest_amount );
					}else if( $columnKey == 'accrued_interest' ){
						$columnsDataVal = number_format( $currentDaySaving );
					}
					$row[$columnKey] = $columnsDataVal;
				}

			}
			$rows[] = $row;
			$sno=$sno+1;

		}

	}

	//total query
	$getCurrentMembersTotals = $wpdb->get_results("SELECT * FROM $tableCsrSavings WHERE 1 AND `email` = '".$refAccount."' $filter_qry ORDER BY $orderby $order");

	if( $getCurrentMembersTotals ){
		foreach( $getCurrentMembersTotals as $getCurrentMembersTotal ){

			$interest_amount = 0;
			$currentDaySaving = 0;
			$interest_amount_by_periods = 0;
			try{

				$startDateObj = DateTime::createFromFormat('d/m/Y', $getCurrentMembersTotal->saving_start_date);
				$currentDateObj = DateTime::createFromFormat( 'd/m/Y', date_i18n('d/m/Y') );

				$startDate = DateTime::createFromFormat( 'Y-m-d', $startDateObj->format('Y-m-d') );
				$currentDate = DateTime::createFromFormat( 'Y-m-d', $currentDateObj->format('Y-m-d') );

				$interval = $startDate->diff($currentDate);
				$intervalNumber = $interval->format('%R%a');

				if( $getCurrentMembersTotal->saved_amount > 0 && $getCurrentMembersTotal->saving_interest > 0 ){
					$interest_amount = round( $getCurrentMembersTotal->saved_amount * $getCurrentMembersTotal->saving_interest / 100 );
				}
				if( $getCurrentMembersTotal->saved_amount > 0 && $getCurrentMembersTotal->saving_interest > 0 ){
					$interest_amount_by_periods = ( $getCurrentMembersTotal->saved_amount * $getCurrentMembersTotal->saving_interest / 100 ) / $getCurrentMembersTotal->saving_periods;
				}
				$totalDaysCount = 0;
				$intInterval = (int)$interval->format('%a');
				// echo $intervalNumber;
				if( $intervalNumber >= 0 && $intInterval <= $getCurrentMembersTotal->saving_periods ){
					$totalDaysCount = $intInterval;
				}else if( $intervalNumber < 0 ){
					$totalDaysCount = 0;
				}else{
					$totalDaysCount = $getCurrentMembersTotal->saving_periods;
				}
				$currentDaySaving = round( $totalDaysCount * $interest_amount_by_periods );
				// $accrued_interest_total += $totalDaysCount * $interest_amount_by_periods;
				$accrued_interest_total += $currentDaySaving;
				$totalSavedAmount += $getCurrentMembersTotal->saved_amount;
				$totalSavedAmountInterest += $interest_amount;
			}catch(\Throwable $th){
				$interest_amount = 0;
				$currentDaySaving = 0;
			}

		}

		$row = array();
		$row['id'] = __('Total', CIP_TXTDOMAIN);
		$row['status'] = '-';
		$row['reference'] = '-';
		$row['saved_amount'] = number_format( $totalSavedAmount );
		$row['accrued_interest'] = number_format( $accrued_interest_total );
		$row['interest_due'] = number_format( $totalSavedAmountInterest );
		$row['saving_interest'] = '-';
		$row['saving_periods'] = '-';
		$row['saving_start_date'] = '-';
		$row['saving_end_date'] = '-';
		$rows[] = $row;

	}

	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_countries_management_table_loader','cip_countries_management_table_loader_cb');
function cip_countries_management_table_loader_cb(){
	global $wpdb;

	$GF_Field_Address = new GF_Field_Address();
	$countries = $GF_Field_Address->get_countries();

	$total = count( $countries );

	$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';

	if( isset( $_POST['search'] ) && !empty( $_POST['search'] ) ){
		$inputSearch = preg_quote( $_POST['search'], '~');
		$countries = preg_filter('~' . $inputSearch . '~i', '$0', $countries);
		$total = count( $countries );
	}

	$countriesData = array_slice( $countries, $offset, $limit );


	$cipDisabledCountries = get_option( 'cipDisabledCountries' );
	$cipDisabledCountries = maybe_unserialize( $cipDisabledCountries );

	$rows = array();

	if( $countriesData ){
		$loopCount = 0;
		foreach( $countriesData as $country ){

			$isDisableCountry = ( in_array( $country, $cipDisabledCountries ) ) ? 0 : 1;
			$label = ( $isDisableCountry ) ? 'Enabled' : 'Disabled';

			$row = array();
			$row['country_names'] = $country;
			$row['action'] = '<div class="custom-control custom-switch mb-0"><input type="checkbox" class="custom-control-input countries_management_chkbox" name="countryName" value="'.$country.'" id="country_'. $loopCount .'" data-_micro="'.wp_create_nonce('_Micro_CountriesManagement_Micro_').'" '. checked( 1, $isDisableCountry, false ).' /><label class="custom-control-label" for="country_'. $loopCount .'">'. $label .'</label></div>';

			$rows[] = $row;
			$loopCount++;
		}
	}
	$out = array(
		'total'			=>	$total,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
/**
 * Function to return data to withdrawals block address list
 */
add_action('wp_ajax_cip_withdrawal_block_address_list_table_loader','cip_cip_withdrawal_block_address_list_table_loader_cb');
function cip_cip_withdrawal_block_address_list_table_loader_cb(){
	global $wpdb;
	$tableWithdrawalBlockAddress = $wpdb->prefix.'withdrawal_block_address';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalBlockAddress WHERE 1");

	$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( $_POST['search'] ) ){
		$filter_qry .= " AND ( `address_name` like '%" . $_POST['search'] . "%' OR `withdrawal_block_address` like '%" . $_POST['search'] . "%')";
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableWithdrawalBlockAddress WHERE 1 $filter_qry");
	}

	$getAddresses = $wpdb->get_results("SELECT * FROM $tableWithdrawalBlockAddress WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$rows = array();

	if( $getAddresses ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getAddresses as $getAddress ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'address_name'				=>	__('address_name', CIP_TXTDOMAIN),
				'withdrawal_block_address'	=>	__('withdrawal_block_address', CIP_TXTDOMAIN),
				'internal_note'	=>	__('internal_note', CIP_TXTDOMAIN),
			);

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getAddress->$columnKey;
					if( $columnKey == 'withdrawal_block_address' ){
						$columnsDataVal = $getAddress->withdrawal_block_address;
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<a class="eth_address" href="https://etherscan.io/address/'. $columnsDataVal . '" target="_blank" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}

				$encryptId = base64_encode($getAddress->id . md5('CIP_WithdrawalBlockAdress_CIP'));
				$data_micro = wp_create_nonce( $getAddress->id . md5('CIP_WithdrawalBlockAdress_CIP') );

				$row['action'] = '<a href="javascript:void(0);" class="delete-withdrawal-block-address" data-delete="'. $encryptId .'" data-address="'.$getAddress->withdrawal_block_address.'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt"></i></a>';
			}
			$rows[] = $row;
			$sno=$sno+1;

		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
/**
 * Function to return data to corporate user list
 */
add_action('wp_ajax_corporate_users_list_loader','cip_corporate_users_list_loader');
function cip_corporate_users_list_loader(){
	global $wpdb;
	$tableCorporateUsers = $wpdb->prefix.'corporate_users';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCorporateUsers WHERE `status`=1");

	$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'] : 'asc';

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	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 `status`=1 $filter_qry");
	}

	$getCorporateUsers = $wpdb->get_results("SELECT * FROM $tableCorporateUsers WHERE `status`=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getCorporateUsers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCorporateUsers as $getCorporateUser ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'first_name' =>	__('number', CIP_TXTDOMAIN),
				'last_name' =>	__('number', CIP_TXTDOMAIN),
				'email' =>	__('number', CIP_TXTDOMAIN),
				'eth_address' =>	__('number', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getCorporateUser->$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" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}

					$encryptId = base64_encode($getCorporateUser->id . md5('CIP_CorporateUser_CIP'));
					$data_micro = wp_create_nonce( $getCorporateUser->id . md5('CIP_CorporateUser_CIP') );
					$row[$columnKey] = $columnsDataVal;
				}
				$row['action'] = '<a href="javascript:void(0);" class="edit-corporate-user ml-3" data-edit="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Edit', CIP_TXTDOMAIN).'"><i class="fas fa-pencil-alt"></i></a><a href="javascript:void(0);" class="delete-corporate-user ml-3" data-delete="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Delete', CIP_TXTDOMAIN).'"><i class="fas fa-trash-alt"></i></a>';
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_corporate_user_request_withdrawal_list_loader','cip_corporate_user_request_withdrawal_list_loader_cb');
function cip_corporate_user_request_withdrawal_list_loader_cb(){
	global $wpdb;
	$tableCorporateUsers = $wpdb->prefix.'corporate_users';
	$user_id = get_current_user_id();
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCorporateUsers WHERE 1 ORDER BY `id` DESC");

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 500;
	$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'] : 'asc';
	$isSelectAll = isset( $_POST['isSelectAll'] ) ? $_POST['isSelectAll'] : 0;
	$tokenType = isset( $_POST['tokenType'] ) ? $_POST['tokenType'] : 'csr';

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	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 ORDER BY `id` DESC");
	}

	$getCurrentCorporateUsers = $wpdb->get_results("SELECT * FROM $tableCorporateUsers WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$saUserData = get_user_by( 'id', $user_id );
	$columnsArr = array(
		'first_name' 			=> __( 'First Name', CIP_TXTDOMAIN),
		'last_name' 			=> __( 'Last Name', CIP_TXTDOMAIN),
		'email'	 				=> __( 'Email', CIP_TXTDOMAIN),
		'eth_address' 			=> __( 'CSR Wallet Address', CIP_TXTDOMAIN),
		'balance_csr_central' 	=> __( 'Balance (CSR Central)', CIP_TXTDOMAIN),
		'balance_blockchain' 	=> __( 'Balance (Blockchain)', CIP_TXTDOMAIN)
	);

	$total_balance_csr_central = 0;
	$total_balance_blockchain = 0;

	$rows = array();
	if( $getCurrentCorporateUsers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentCorporateUsers as $getCurrentMember ){
			$row = array();
			$row['id'] = $sno;

			if( $isSelectAll == 1 ){
				$currentSelected = 1;
			}else if( $isSelectAll == 0 ){
				$currentSelected = 1;
			}
			$rowEncryptId = base64_encode( $getCurrentMember->id . md5('CIP_CURWSELECTION_PIC') );

			$balance_blockchain = cip_get_ether_balance( $getCurrentMember->eth_address, $tokenType );
			if( $balance_blockchain == '-' || $balance_blockchain < 0 ){
				$balance_blockchain = 0;
			}

			// $userData = get_user_by( 'email', $getCurrentMember->email );
			// if( $userData ){
			// }
			$balance_csr_central = get_user_csr_balance( $getCurrentMember->email, 'available', $tokenType );

			$requestedPendingBalance = 0;
			$csr_balance_total = get_user_csr_balance( $getCurrentMember->email, 'total', $tokenType );

			try {
				$requestedPendingBalance = $csr_balance_total - $balance_csr_central;
			} catch (\Throwable $th) {
				$requestedPendingBalance = 0;
			}

			$row['rowiddata'] = '<input type="checkbox" name="rowiddata" class="rowiddata" data-balance_blockchain="'. $balance_blockchain .'" data-balance_csr_central="'. $balance_csr_central .'" value="'.$rowEncryptId.'" '.checked( $isSelectAll, $currentSelected, false ).' />';
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$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" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$row['balance_csr_central'] = number_format( $balance_csr_central, 2 );
			$row['balance_blockchain'] = number_format( $balance_blockchain, 2 );
			$row['pending_balance'] = number_format( $requestedPendingBalance, 2 );

			// $row['action'] = '<a href="'.$editLink.'" title="edit"><i class="fas fa-edit"></i></a>'.$unVerifyLink;
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows,
		// 'total_amount_due'	=>	number_format( $total_amount_due ),
	);
	echo wp_json_encode( $out );
	exit;
}

add_action('wp_ajax_load_hall_of_fame','cip_load_hall_of_fame_cb');
add_action('wp_ajax_nopriv_load_hall_of_fame','cip_load_hall_of_fame_cb');
function cip_load_hall_of_fame_cb(){

	global $wpdb;
	$data_content = '<div class="hall_of_fame_list_row">';
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_id = get_current_user_id();
	$user_id = -1;

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement");
	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement");

	$limit = isset( $_POST['postsPerPage'] ) ? $_POST['postsPerPage'] : 10;
	$offset = isset( $_POST['page'] ) ? ($_POST['page']-1)*$limit : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$filter_qry = "";
	$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))';
	}
	/*$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		$count = 1;
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'fullname' ){
				$companyEmails = array();
				$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$filterData."%' AND `company_name_toggle` = 1");
				if( $getCompanies ){
					foreach( $getCompanies as $getCompany ){
						$companyEmails[] = $getCompany->email;
					}
				}
				if( !empty( $companyEmails ) ){
					$companyEmail = implode( "','",$companyEmails );
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' OR `email` IN ('".$companyEmail."') )";
				}else{
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' )";
				}
			}else{
				$filter_qry .= ( $filterKey == 'retire_amount' ) ? " AND `$filterKey` = $filterData" : " AND `$filterKey` LIKE '%" . $filterData . "%'";
			}
			// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
			$count++;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}*/
	$amountdata = json_decode( stripslashes( $_REQUEST['amountfilterByConditionPoolRef'] ), true );
	if( !empty( $amountdata ) ){
		$count = 1;
		// foreach( $amountdata as $filterKey => $filterData ){
		// 	if(){

		// 	}
		// 	// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
		// 	$count++;
		// }

		if(isset($amountdata['fullname']) && $amountdata['fullname'] != ""){
			$name_parts = explode(" ", $amountdata['fullname']);
			if(!empty($name_parts[1])){
				$last_name = "OR `last_name` LIKE '%" . $name_parts[1] . "%'";
			}else{
				$last_name = "";
			}
			$companyEmails = array();
			$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$name_parts[0]."%' AND `company_name_toggle` = 1");
			if( $getCompanies ){
				foreach( $getCompanies as $getCompany ){
					$companyEmails[] = $getCompany->email;
				}
			}
			if( !empty( $companyEmails ) ){
				$companyEmail = implode( "','",$companyEmails );
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." OR `email` IN ('".$companyEmail."') )";
			}else{
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." )";
			}
		}

		if(isset($amountdata['eth_address']) && $amountdata['eth_address'] != ""){
			$filter_qry .= " AND `eth_address` LIKE '%" . $amountdata['eth_address'] . "%'";
		}
		if(isset($amountdata['retire_transhash']) && $amountdata['retire_transhash'] != ""){
			$filter_qry .= " AND `retire_transhash` LIKE '%" . $amountdata['retire_transhash'] . "%'";
		}

		// if (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "" && isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` BETWEEN '$start_amount' AND '$end_amount'";
		// }
		// // Check for only start amount (greater than)
		// elseif (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$filter_qry .= " AND `retire_amount` > '$start_amount'";
		// }
		// // Check for only end amount (less than)
		// elseif (isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` < '$end_amount'";
		// }
		if(isset($amountdata['filter_type']) && $amountdata['filter_type'] == "retire_token_type" && isset($amountdata['token_type']) && $amountdata['token_type'] != "")
		{
			$filter_qry .= " AND `token` = '".$amountdata['token_type']."'";
		}
		if(isset($amountdata['retire_amount_type']) && $amountdata['retire_amount_type'] != ""){
			if(isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != ""){
				$filter_qry .= " AND `retire_amount` ".$amountdata['retire_amount_type']." '".$amountdata['retire_amount_start']."'";
			}
		}

		if (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "" && isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` BETWEEN '$start_amount' AND '$end_amount'";
		}
		// Check for only start amount (greater than)
		elseif (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$filter_qry .= " AND `retire_confirm_date` > '$start_amount'";
		}
		// Check for only end amount (less than)
		elseif (isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` < '$end_amount'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}

	if( isset($_POST['letter']) && $_POST['letter'] != ""){
		$companyEmails = array();
		$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '".$_POST['letter']."%' AND `company_name_toggle` = 1");
		if( $getCompanies ){
			foreach( $getCompanies as $getCompany ){
				$companyEmails[] = $getCompany->email;
			}
		}
		if( !empty( $companyEmails ) ){
			$companyEmail = implode( "','",$companyEmails );
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' OR `email` IN ('".$companyEmail."') )";
		}else{
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' )";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}


	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	// $getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
	$user_id = get_current_user_id();

	// echo "ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset";

	$csr_wallet_api_mode = ( !empty( get_option('csr_wallet_api_mode') ) ) ? get_option('csr_wallet_api_mode') : 'test';
	$endpoint = ( $csr_wallet_api_mode == 'live' ) ? 'https://etherscan.io/tx/' : 'https://sepolia.etherscan.io/tx/';
	$rows = array();
	if( $getRetirements ){
		foreach( $getRetirements as $getRetirement ){
			$row = array();
			$columnsDataVal = '—';
			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>';
			}else{
				$columnsDataVal = '—';
			}

			$retire_transhash = '—';
			if( !empty( $getRetirement->retire_transhash ) ){
				$transhashDataValMask = substr($getRetirement->retire_transhash, 0, 10) . '...' . substr($getRetirement->retire_transhash, -10);
				$retire_transhash = '<a href="'.$endpoint.$getRetirement->retire_transhash.'" target="_blank" class="transhash_view" data-toggle-tt="tooltip" data-placement="top" title="'.$getRetirement->retire_transhash.'" >'.$transhashDataValMask.'</a>';
			}else{
				$retire_transhash = '—';
			}

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

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

			$getTokenData = $wpdb->get_row("SELECT `first_name`,`last_name` FROM $tableTokenHolder WHERE email IN ('".$getRetirement->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 `company_name_toggle`,`company_name`,`status`,`member_logo`,`member_url` FROM $tableRetirementSetting WHERE email = '".$getRetirement->email."' ");
			// $getRetirementSetting = $wpdb->get_row("SELECT `company_name_toggle`,`company_name`,`status`,`member_logo`,`member_url` FROM $tableRetirementSetting WHERE email IN (".$getRetirement->email.")");
			$member_logo_img = "";
			if( $getRetirementSetting ){
				if( $getRetirementSetting->company_name_toggle == 1 && !empty( $getRetirementSetting->company_name ) ){
					$hiLine = $getRetirementSetting->company_name;
				}
				if( $getRetirementSetting->status == 1 && !empty( $getRetirementSetting->member_logo ) ){
					// $member_logo_img = '<img class="member_logo_img" src="'.base64_encode($getRetirementSetting->member_logo).'" class="img-responsive" />';
					$member_logo_img = '<img class="member_logo_img" src="data:image/jpg;charset=utf8;base64,'.base64_encode($getRetirementSetting->member_logo).'" class="img-responsive" />';
					if( !empty( $getRetirementSetting->member_url ) ){
						$member_logo_img = '<a href="'. $getRetirementSetting->member_url .'" target="_blank">'.$member_logo_img.'</a>';
					}
				}
				if( $getRetirementSetting->status == 1 && !empty( $getRetirementSetting->member_url ) ){
					$hiLine = '<a href="'. $getRetirementSetting->member_url .'" target="_blank">'.$hiLine.' <i class="fas fa-external-link-alt"></i></a>';
				}
			}

			$row['member_logo'] = $member_logo_img;
			$row['fullname'] = $hiLine;
			$row['eth_address'] = $columnsDataVal;
			$row['retire_transhash'] = $retire_transhash;
			// $row['retire_transhash'] = $select_abc;

			$retire_amount_grid = "";
			$retire_amount = floatval( bcadd( $getRetirement->retire_amount, 0, 2) );
			if (fmod($retire_amount, 1) !== 0.0) {
				$row['retire_amount'] = $retire_amount_grid = cip_number_format($getRetirement->retire_amount,true)." ".$getRetirement->token;
			}else{
				$row['retire_amount'] = $retire_amount_grid = cip_number_format($getRetirement->retire_amount,false)." ".$getRetirement->token;
			}

			$row['retire_confirm_date'] = $retire_confirm_date;

			$data_content .= '<div class="item">
								<div class="item_row">';
			if($member_logo_img){
				$data_content .= '<div class="item_img">'.$member_logo_img.'</div>';
            }


            $data_content .= '<div class="item_contain">
									<div class="item_inner_grup">
										<h4>'.$hiLine.'</h4>
									</div>
									<div class="item_inner_grup">
										<p class="cc_title">Address</p>
										<p class="cc_total">'.$columnsDataVal.'</p>
									</div>
									<div class="item_inner_grup">
										<p class="cc_title">Transaction hash</p>
										<p class="cc_total">'.$retire_transhash.'</p>
									</div>
									<div class="item_inner_grup row align-items-end justify-content-between">
										<!-- <div class="row align-items-end"> -->
											<div>
												<p class="cc_title">Amount</p>
												<p class="cc_total  mini-total">'.$retire_amount_grid.'</p>
											</div>
											<div class="">
												<p class="cc_title w-100 text-left new">Age</p>
												<p class="cc_total text-right">'.$retire_confirm_date.'</p>
											</div>
										<!-- </div> -->

									</div>
								</div>
							</div>
						</div>';

			// $row['html_data'] = $data_content;
			$rows[] = $row;
		}
	}else{
		$data_content = '<div class="text-center p-5">No hall of fame found</div>';
	}
	$data_content .= '</div>';
	$out = array(
		'total'		=>	$total_items,
		'html'		=>	$data_content,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
	?>

    <?php
	// exit;
}

add_action('wp_ajax_count_hall_of_fame','cip_count_hall_of_fame_cb');
add_action('wp_ajax_nopriv_count_hall_of_fame','cip_count_hall_of_fame_cb');
function cip_count_hall_of_fame_cb(){
	global $wpdb;
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$tableTokenHolder = $wpdb->prefix.'token_holder';
	$tableRetirementSetting = $wpdb->prefix.'retirement_setting';
	$user_id = get_current_user_id();
	$user_id = -1;

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement");
	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement");

	$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 = "";
	$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))';
	}
	/*$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		$count = 1;
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'fullname' ){
				$companyEmails = array();
				$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$filterData."%' AND `company_name_toggle` = 1");
				if( $getCompanies ){
					foreach( $getCompanies as $getCompany ){
						$companyEmails[] = $getCompany->email;
					}
				}
				if( !empty( $companyEmails ) ){
					$companyEmail = implode( "','",$companyEmails );
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' OR `email` IN ('".$companyEmail."') )";
				}else{
					$filter_qry .= " AND ( `first_name` LIKE '%" . $filterData . "%' OR `last_name` LIKE '%" . $filterData . "%' )";
				}
			}else{
				$filter_qry .= ( $filterKey == 'retire_amount' ) ? " AND `$filterKey` = $filterData" : " AND `$filterKey` LIKE '%" . $filterData . "%'";
			}
			// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
			$count++;
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}*/
	$amountdata = json_decode( stripslashes( $_REQUEST['amountfilterByConditionPoolRef'] ), true );
	if( !empty( $amountdata ) ){
		$count = 1;
		// foreach( $amountdata as $filterKey => $filterData ){
		// 	if(){

		// 	}
		// 	// $filter_qry .= " AND `$filterKey` LIKE '%" . $filterData . "%'";
		// 	$count++;
		// }

		if(isset($amountdata['fullname']) && $amountdata['fullname'] != ""){
			$name_parts = explode(" ", $amountdata['fullname']);
			if(!empty($name_parts[1])){
				$last_name = "OR `last_name` LIKE '%" . $name_parts[1] . "%'";
			}else{
				$last_name = "";
			}
			$companyEmails = array();
			$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '%".$name_parts[0]."%' AND `company_name_toggle` = 1");
			if( $getCompanies ){
				foreach( $getCompanies as $getCompany ){
					$companyEmails[] = $getCompany->email;
				}
			}
			if( !empty( $companyEmails ) ){
				$companyEmail = implode( "','",$companyEmails );
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." OR `email` IN ('".$companyEmail."') )";
			}else{
				$filter_qry .= " AND ( `first_name` LIKE '%" . $name_parts[0] . "%' ".$last_name." )";
			}
		}

		if(isset($amountdata['eth_address']) && $amountdata['eth_address'] != ""){
			$filter_qry .= " AND `eth_address` LIKE '%" . $amountdata['eth_address'] . "%'";
		}
		if(isset($amountdata['retire_transhash']) && $amountdata['retire_transhash'] != ""){
			$filter_qry .= " AND `retire_transhash` LIKE '%" . $amountdata['retire_transhash'] . "%'";
		}

		// if (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "" && isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` BETWEEN '$start_amount' AND '$end_amount'";
		// }
		// // Check for only start amount (greater than)
		// elseif (isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != "") {
		// 	$start_amount = $amountdata['retire_amount_start'];
		// 	$filter_qry .= " AND `retire_amount` > '$start_amount'";
		// }
		// // Check for only end amount (less than)
		// elseif (isset($amountdata['retire_amount_end']) && $amountdata['retire_amount_end'] != "") {
		// 	$end_amount = $amountdata['retire_amount_end'];
		// 	$filter_qry .= " AND `retire_amount` < '$end_amount'";
		// }
		if(isset($amountdata['retire_amount_type']) && $amountdata['retire_amount_type'] != ""){
			if(isset($amountdata['retire_amount_start']) && $amountdata['retire_amount_start'] != ""){
				$filter_qry .= " AND `retire_amount` ".$amountdata['retire_amount_type']." '".$amountdata['retire_amount_start']."'";
			}
		}

		if (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "" && isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` BETWEEN '$start_amount' AND '$end_amount'";
		}
		// Check for only start amount (greater than)
		elseif (isset($amountdata['retire_confirm_date_start']) && $amountdata['retire_confirm_date_start'] != "") {
			$start_amount = $amountdata['retire_confirm_date_start'];
			$filter_qry .= " AND `retire_confirm_date` > '$start_amount'";
		}
		// Check for only end amount (less than)
		elseif (isset($amountdata['retire_confirm_date_end']) && $amountdata['retire_confirm_date_end'] != "") {
			$end_amount = $amountdata['retire_confirm_date_end'];
			$filter_qry .= " AND `retire_confirm_date` < '$end_amount'";
		}
		elseif (isset($amountdata['token_type']) && $amountdata['token_type'] != "") {
			$filter_qry .= " AND `token` = '".$amountdata['token_type']."'";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}

	if( isset($_POST['letter']) && $_POST['letter'] != ""){
		$companyEmails = array();
		$getCompanies = $wpdb->get_results("SELECT `email` FROM $tableRetirementSetting WHERE 1 AND `company_name` like '".$_POST['letter']."%' AND `company_name_toggle` = 1");
		if( $getCompanies ){
			foreach( $getCompanies as $getCompany ){
				$companyEmails[] = $getCompany->email;
			}
		}
		if( !empty( $companyEmails ) ){
			$companyEmail = implode( "','",$companyEmails );
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' OR `email` IN ('".$companyEmail."') )";
		}else{
			$filter_qry .= " AND ( `first_name` LIKE '" . $_POST['letter'] . "%' OR `last_name` LIKE '" . $_POST['letter'] . "%' )";
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `id` DESC");
	}else{
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry");
	}


	$getRetirements = $wpdb->get_results("SELECT * FROM $tableRetirement WHERE retire_status = 1 AND $visibility_qry $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	wp_send_json_success(array("total_posts" => $total_items));
    die();
}

add_action('wp_ajax_count_az_hall_of_fame','cip_count_az_hall_of_fame_cb');
add_action('wp_ajax_nopriv_count_az_hall_of_fame','cip_count_az_hall_of_fame_cb');
function cip_count_az_hall_of_fame_cb(){
	$search = $_POST['search'];
    $letters = range('A', 'Z');

    // echo json_encode(['letters' => $letters]);
	wp_send_json_success(array("letters" => $letters));
    die();
}
/**
 * Function to return data to csr pool report list
 */
add_action('wp_ajax_csr_pool_report_list_table_loader','cip_csr_pool_report_list_table_loader_cb');
function cip_csr_pool_report_list_table_loader_cb(){
	global $wpdb;
	$tableCsrPoolReports = $wpdb->prefix.'csr_pool_reports';

	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrPoolReports WHERE 1");

	$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 = "";

	$filterByConditionsPoolRef = json_decode( stripslashes( $_REQUEST['filterByConditionPoolRef'] ), true );
	$filterByPoolRef = "";
	$filterByValuePoolRef = "";
	if( !empty( $filterByConditionsPoolRef ) ){
		$filterByPoolRef = $filterByConditionsPoolRef['filter_condition_type_pool_reference'];
		if( $filterByPoolRef == 'is_exactly_simple' ){
			$filterByValuePoolRef = array_filter( explode(',', $filterByConditionsPoolRef['filter_condition_value_pool_reference_bulk'] ) );
		}else{
			$filterByValuePoolRef = $filterByConditionsPoolRef['filter_condition_value_pool_reference'];
		}
	}

	$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'];
		}
	}

	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );

	if( $filterByPoolRef != 'none' ){
		$filters['pool_reference'] = $filterByValuePoolRef;
	}

	if( $filterByDistributionWeek != 'none' ){
		$filters['distribution_week'] = $filterByValueDistributionWeek;
	}

	$isNumericColumn = array('csr_initial_amount', 'csr_distributed', 'amount_due');

	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'distribution_status' ){
				$filter_qry .= " AND `$filterKey` = '" . $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( $filterKey == 'pool_reference' ){
				if( $filterByPoolRef != 'none' ){
					if( $filterByPoolRef == 'is_exactly' || $filterByPoolRef == 'is_exactly_simple' && !empty( $filterData ) ){
						$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
					}
				}
			}else if( $filterKey == 'distribution_week' ){
				if( $filterByDistributionWeek != 'none' ){
					if( $filterByDistributionWeek == 'is_exactly' || $filterByDistributionWeek == 'weeks_before' || $filterByDistributionWeek == 'is_exactly_simple' && !empty( $filterData ) ){
						$filter_qry .= " AND `$filterKey` IN ('" . implode("','", $filterData) . "')";
					}
				}
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrPoolReports WHERE 1 $filter_qry ORDER BY `id` DESC");
	}

	$getDatas = $wpdb->get_results("SELECT * FROM $tableCsrPoolReports WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");

	$rows = array();

	$csr_initial_amount_total = 0;
	$csr_distributed_total = 0;
	$amount_due_total = 0;

	$getTotalData = $wpdb->get_row("SELECT COALESCE(SUM(`csr_initial_amount`),0) as `csr_initial_amount_total`, COALESCE(SUM(`csr_distributed`),0) as `csr_distributed_total`, COALESCE(SUM(`amount_due`),0) as `amount_due_total` FROM `$tableCsrPoolReports` WHERE 1 $filter_qry");

	if( $getTotalData->csr_initial_amount_total ){
		$csr_initial_amount_total = $getTotalData->csr_initial_amount_total;
	}
	if( $getTotalData->csr_distributed_total ){
		$csr_distributed_total = $getTotalData->csr_distributed_total;
	}
	if( $getTotalData->amount_due_total ){
		$amount_due_total = $getTotalData->amount_due_total;
	}

	if( $getDatas ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getDatas as $getData ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'distribution_status'			=>	'distribution_status',
				'pool_reference'				=>	'pool_reference',
				'distribution_week'				=>	'distribution_week',
				'amount_due_condition_value'	=>	'amount_due_condition_value',
				'csr_initial_amount'			=>	'csr_initial_amount',
				'csr_distributed'				=>	'csr_distributed',
				'amount_due'					=>	'amount_due',
			);

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getData->$columnKey;
					if( $columnKey == 'csr_initial_amount' || $columnKey == 'csr_distributed' || $columnKey == 'amount_due' ){
						$columnsDataVal = number_format( $columnsDataVal );
					}
					if( $columnKey == 'amount_due_condition_value' ){
						$columnsDataVal = $getData->amount_due_condition.' '.$columnsDataVal;
					}
					$row[$columnKey] = $columnsDataVal;
				}

				$encryptId = base64_encode($getData->id . md5('CIP_CSRPoolReports_CIP'));
				$data_micro = wp_create_nonce( $getData->id . md5('CIP_CSRPoolReports_CIP') );

				$row['action'] = '<a href="javascript:void(0);" class="edit-pool-report ml-3" data-edit="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="Edit"><i class="fas fa-pencil-alt"></i></a> <a href="javascript:void(0);" class="delete-pool-report ml-3" data-delete="'. $encryptId .'" data-micro="'.$data_micro.'" data-toggle-tt="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt"></i></a>';
			}
			$rows[] = $row;
			$sno=$sno+1;

		}
		$row = array(
			'id'					=>	'<b>'.__('Total', CIP_TXTDOMAIN).'</b>',
			'distribution_status'	=>	'&mdash;',
			'pool_reference'		=>	'&mdash;',
			'distribution_week'		=>	'&mdash;',
			'amount_due_condition'	=>	'&mdash;',
			'csr_initial_amount'	=>	'<b>'.number_format( $csr_initial_amount_total ).'</b>',
			'csr_distributed'		=>	'<b>'.number_format( $csr_distributed_total ).'</b>',
			'amount_due'			=>	'<b>'.number_format( $amount_due_total ).'</b>',
			'action'				=>	'&mdash;',
		);
		$rows[] = $row;

	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}

/**
 * Function to return data to partial filtered report list
 */
add_action('wp_ajax_partial_filtered_table_loader','cip_partial_filtered_table_loader_cb');
function cip_partial_filtered_table_loader_cb(){

	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();

	$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';

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

		foreach( $columnOrders as $columnOrder ){

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

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

			}

		}

	}

	if( empty( $columnsArr ) ){

		$columnsArr = $defaultColumnsArr;

	}

	$filter_qry = "";

	$filters = json_decode( stripslashes( $_REQUEST['partial_export_filter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if($filterKey != 'action'){
				if($filterKey != '_micro'){

					if( $filterKey == 'pool_ref' || $filterKey == 'corp_approved' || $filterKey == 'username' ){
						$filter_data = array_filter($filterData);
						if(!empty($filter_data)){
							$filter_qry .= ' AND `'.$filterKey.'` IN ("' . implode('", "', $filter_data) . '")';
						}
					}else{
						if($filterData != ""){
							$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
						}
					}
				}
			}
		}
		// $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrPoolReports WHERE 1 $filter_qry ORDER BY `id` DESC");
	}

	if( !empty( $filter_qry ) ){
		$getDatas = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 $filter_qry ORDER BY `id` DESC");
	}else{
		$getDatas = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName");
	}

	$isNumericColumn = array('csr_amount_initial', 'csr_amount_issued', 'amount_due');

	$rows = array();
	if( $getDatas ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getDatas as $getData ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'reference' => 'reference',
				'token' => 'token',
				'csr_amount_initial' => 'csr_amount_initial',
				'csr_amount_issued' => 'csr_amount_issued',
				'amount_due' => 'amount_due',
				'username' => 'username',
				'email' => 'email',
				'eth_address' => 'eth_address',
				'pool_ref' => 'pool_ref',
				'text_1' => 'text_1',
				'text_2' => 'text_2',
				'text_3' => 'text_3',
				'text_4' => 'text_4',
				'text_5' => 'text_5',
				'text_6' => 'text_6',
				'text_7' => 'text_7',
				'text_8' => 'text_8',
				'text_9' => 'text_9',
				'text_10' => 'text_10',
				'corp_approved' => 'corp_approved'
			);

			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getData->$columnKey;

					if( $columnKey == 'eth_address_status' ){

						$verified = false;

						$tableSign = $wpdb->prefix.'eth_sign_validate';

						$getSignedData = $wpdb->get_row("SELECT * FROM $tableSign WHERE email = '".$getData->email."' AND eth_address = '".strtolower( $getData->eth_address )."' AND verify_status = 1 ");

						if( $getSignedData ){

							$verified = true;

						}

						$columnsDataVal = ( $verified ) ? __('Verified',CIP_TXTDOMAIN) : __('Not verified',CIP_TXTDOMAIN);

					}else{

						$columnsDataVal = $getData->$columnKey;
						if( in_array( $columnKey, $isNumericColumn ) ){
							$columnsDataVal = number_format( $getData->$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 = '—';

							}

						}

					}
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;

		}

	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
		'filter_qry'			=>	$filter_qry,
	);
	echo wp_json_encode( $out );
	exit;
}


/**
 * Function to return data to partial filtered report list
 */
add_action('wp_ajax_my_csr_token_holder_table_loader','cip_my_csr_token_holder_table_loader_cb');
function cip_my_csr_token_holder_table_loader_cb(){

	// 	ini_set('display_errors', '1');
	// ini_set('display_startup_errors', '1');
	// error_reporting(E_ALL);
	global $defaultColumnsArr;
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$tableNameCol = $wpdb->prefix.'token_holder_columns';
	$tableAddressPending = $wpdb->prefix.'csr_address_pending';
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
	$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 AND email = '".$refAccount."' ORDER BY `id` DESC");
	$getMembersColumns = $wpdb->get_row("SELECT * FROM $tableNameCol WHERE 1 AND 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];
				}
			}
		}
	}

	/* $isPendingReview = false;
	$pendingAddressLists = $wpdb->get_var(" SELECT COUNT(id) FROM $tableAddressPending WHERE 1 AND email = '".$refAccount."' AND status = 2 AND type = 'request' ORDER BY `id` DESC LIMIT 1");
	if( $pendingAddressLists ){
		$isPendingReview = true;
	} */

	$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 = "";
	
	$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 . "%'";
			}
		}
		$total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableName WHERE 1 AND email = '".$refAccount."' $filter_qry ORDER BY `id` DESC");
	}
	$getDatas = $wpdb->get_results("SELECT * FROM $tableName WHERE 1 AND email = '".$refAccount."' $filter_qry ORDER BY $orderby $order LIMIT $limit OFFSET $offset");
	$rows = array();
	if( $getDatas ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getDatas as $getData ){
			$importedUserData = get_userdata( $getData->imported_by );
			$is_add_eth = false;
			$is_edit_eth = false;
			$row = array();
			$row['id'] = $sno;
			$row['ethid'] = $getData->id;
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getData->$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>';
							if( $getData->sign_verify == 1 ){
								$columnsDataVal .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />';
							}
							$is_edit_eth = true;
						}else{
							$is_add_eth = true;
							$columnsDataVal = '—';
						}
					}
					if( $columnKey == 'notes_internal' || $columnKey == 'notes_external' ){
						$columnsDataVal = cip_trim_notes( $columnsDataVal );

						$columnsDataVal150 = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 150, '......');
						$columnsDataVal = wp_html_excerpt( strip_shortcodes( $columnsDataVal ), 20, '<a href="javascript:void(0);" class="modelpop_notes" data-toggle="modal" data-target="#viewMoreModal" data-id="'.$getData->id.'" data-viewmore="'.wpautop( $columnsDataVal ).'" data-toggle-tt1="tooltip" data-placement1="top" title="'.$columnsDataVal150.'" ><img src="'.CIP_PLUGIN_FOLDER.'/images/view-more.png" class="view-more-notes" /></a>' );
						if( !empty( $columnsDataVal ) ){
							$columnsDataVal = '<div class="width_length_20_hr">' . $columnsDataVal . '</div>';
						}
					}
					if( $columnKey == 'saving_date' || $columnKey == 'saving_start_date' ){
						$columnsDataVal = '—';
						try {
							$DateObj = DateTime::createFromFormat( 'd/m/Y', $getData->$columnKey );
							$columnsDataVal = $DateObj->format('d-m-Y');
						} catch (\Throwable $th) {
							$columnsDataVal = '—';
						}
					}
					/* if( $columnKey == 'notes_external' && $getData->corp_approved != 'Issued' ){
						if( $isPendingReview && !empty( $getData->note_10 ) ){
							$columnsDataVal = __('Address update pending. Check back in 2 working days.',CIP_TXTDOMAIN);
						}
					} */
					if($columnKey == 'pool_ref'){
						$pool_ref_condition = false;
						if($columnsDataVal == 'F' || $columnsDataVal == 'H' || $columnsDataVal == 'J'){
							$pool_ref_condition = true;
						}
					}
					if($columnKey == 'csr_amount_initial' || $columnKey == 'csr_amount_issued' || $columnKey == 'amount_due' || $columnKey == 'saved_amount'){
						$row[$columnKey] = cip_number_format($columnsDataVal,false);
					}else{
						$row[$columnKey] = $columnsDataVal;
					}
				}
			}
			$save_link = "";
			$verify_link = "";
			$unsave_link = "";
			$action_html = "";

			if( !empty( $getData->eth_address ) ){
				if( $getData->sign_verify != 1 ){
					$verify_link = '<a href="javascript:void(0);" class="signVerifyBtn mr-2 ml-2" data-toggle-tt="tooltip" data-placement="top" title="'.__('Verify your CSR Wallet address using MetaMask (Free).',CIP_TXTDOMAIN).'"><i class="fas fa-user-check"></i></a>';
				}
				$save_link = '<a href="javascript:void(0);" class="mr-2 ml-2" title="Saving"><i class="fas fa-money-check-alt" data-toggle-tt="tooltip" data-placement="top" title="'.__('Saving and Staking will move to CSR Wallet soon.',CIP_TXTDOMAIN).'"></i> </a>';
			}



			if( $getData->sign_verify == 1 && !empty( $getData->saved_amount ) && empty( $getData->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>';
			}
			$action_html = '<a class="fa fa-eye mr-2 ml-2" href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title="Coming soon"></a>';
			
			$row['action'] = $action_html . $verify_link . $save_link . $unsave_link;

			$encryptToken = base64_encode( $getData->id . md5( $getData->token ));

			$row['tokenEncrypt'] = $encryptToken;
			$row['tokenType'] = strtolower( $getData->token );

			$rows[] = $row;
			$sno=$sno+1;

		}

	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_Orders_Invoices_table_loader','cip_Orders_Invoices_table_loader');
function cip_Orders_Invoices_table_loader(){
	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 ArchiveStatus = '".$ArchiveStatus."' 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 ){
			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 ArchiveStatus = '".$ArchiveStatus."' $filter_qry");
	}

	$getinvoicetable = $wpdb->get_results("SELECT * FROM $invoice WHERE ArchiveStatus = '".$ArchiveStatus."' $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$rows = array();
	if( $getinvoicetable ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getinvoicetable as $getInvoiceItem ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'ProformaInvoiceNumber' =>	__('ProformaInvoiceNumber', CIP_TXTDOMAIN),
				'Date' =>	__('Date', CIP_TXTDOMAIN),
				'InvoiceNumber' =>	__('InvoiceNumber', CIP_TXTDOMAIN),
				'PaidDate' =>	__('PaidDate', CIP_TXTDOMAIN),
				'Package' =>	__('Package', CIP_TXTDOMAIN),
				'ProductPrice' =>	__('ProductPrice', CIP_TXTDOMAIN),
				'Kgs' =>	__('Kgs', CIP_TXTDOMAIN),
				'Status' =>	__('Status', CIP_TXTDOMAIN),
				'Type' =>	__('Type', CIP_TXTDOMAIN),
				'POVATAmount' =>	__('POVATAmount', CIP_TXTDOMAIN),
				'PONetAmount' =>	__('PONetAmount', CIP_TXTDOMAIN),
				'POGrossAmount' =>	__('POGrossAmount', CIP_TXTDOMAIN),
				'PoVATPercentage' =>	__('PoVATPercentage', CIP_TXTDOMAIN),
				'NetAmount' =>	__('NetAmount', CIP_TXTDOMAIN),
				'GrossAmount' =>	__('GrossAmount', CIP_TXTDOMAIN),
				'VATPercentage' =>	__('VATPercentage', CIP_TXTDOMAIN),
				'Website' =>	__('Website', CIP_TXTDOMAIN),
				'BusinessName' =>	__('BusinessName', CIP_TXTDOMAIN),
				'BusinessCategory' =>	__('BusinessCategory', CIP_TXTDOMAIN),
				'Employees' =>	__('Employees', CIP_TXTDOMAIN),
				'PlasticWaste' =>	__('PlasticWaste', CIP_TXTDOMAIN),
				'PlasticWasteFootprint' =>	__('PlasticWasteFootprint', CIP_TXTDOMAIN),
				'IntroducedBy' =>	__('IntroducedBy', CIP_TXTDOMAIN),
				'Email' =>	__('Email', CIP_TXTDOMAIN),
				'Username' =>	__('Username', CIP_TXTDOMAIN),
				'FirstName' =>	__('FirstName', CIP_TXTDOMAIN),
				'LastName' =>	__('LastName', CIP_TXTDOMAIN),
				'Address1' =>	__('Address1', CIP_TXTDOMAIN),
				'Address2' =>	__('Address2', CIP_TXTDOMAIN),
				'Number' =>	__('Number', CIP_TXTDOMAIN),
				'City' =>	__('City', CIP_TXTDOMAIN),
				'State' =>	__('State', CIP_TXTDOMAIN),
				'State' =>	__('State', CIP_TXTDOMAIN),
				'Zipcode' =>	__('Zipcode', CIP_TXTDOMAIN),
				'token' =>	__('token', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getInvoiceItem->$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" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}
					if($columnKey == 'InvoiceNumber'){
						if(!empty( $columnsDataVal )){
							$columnsDataVal = 'CSR-'.$getInvoiceItem->$columnKey;
						}
					}
					$encryptId = base64_encode($getInvoiceItem->id . md5('CIP_InvoiceItem_CIP'));
					$data_micro = wp_create_nonce( $getInvoiceItem->id . md5('CIP_InvoiceItem_CIP') );
					if( $columnKey == 'ProductPrice' || $columnKey == 'POVATAmount' || $columnKey == 'PONetAmount' || $columnKey == 'POGrossAmount' || $columnKey == 'PoVATPercentage' || $columnKey == 'NetAmount' || $columnKey ==  'GrossAmount' ){
						$columnsDataVal = cip_number_format($columnsDataVal); 
					}
					$row[$columnKey] = $columnsDataVal;
				}
				$id = $getInvoiceItem->id;
				$path = get_site_url();
				if(  $getInvoiceItem->ArchiveStatus == 'No' ) { 
					$action = '';
					if( $getInvoiceItem->Status != 'Paid' ){
						$action .= '<a class="ml-2 order_process" title="View Process" data-toggle-tt="tooltip" archive-id="'.$id.'" micro="'.wp_create_nonce('_CIPxOrderProcessCIP_').'" href="javascript:void(0);"><i class="fa fa-dollar-sign"></i></a>';
					}
					$action .= '<a class="ml-2 archive_status_active" title="Archive" data-toggle-tt="tooltip" archive-id="'.$id.'" href="javascript:void(0);"><i class="fa fa-archive" aria-hidden="true"></i></a>';
					$action .= '<a class="ml-2" title="View Purchase Order" data-toggle-tt="tooltip" target="_blank" href="'.$path.'/wp-content/plugins/cip-helper/includes/pdf/download_pdf.php/?id='.$id.'&paid=0" style="text-decoration:none;"><i class="fas fa-eye"></i></a>';
					if( $getInvoiceItem->Status == 'Paid' ){
						$action .= '<a class="ml-2" title="View Invoice" data-toggle-tt="tooltip" target="_blank" href="'.$path.'/wp-content/plugins/cip-helper/includes/pdf/download_pdf.php/?id='.$id.'&paid=1" style="text-decoration:none;"><i class="fa fa-file"></i></a>'; 
					}
				}else{
					$action = '<a class="ml-2 archive_status_deactive" title="Un-Archive" data-toggle-tt="tooltip"  archive-id="'.$id.'" href="javascript:void(0);"><i class="fas fa-undo"></i></a>'; 
				}
				$row['action'] =  $action;
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
/**
 * Function to load retirement table list
 */
add_action('wp_ajax_mycsr_table_retirment_loader','cip_mycsr_table_retirment_loader');
function cip_mycsr_table_retirment_loader(){
	global $wpdb;
	$tableName = $wpdb->prefix.'token_holder';
	$tableRetirement = $wpdb->prefix.'retirement_data';
	$refAccount = $_SESSION['refAccount'];
	
	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'eth_address, tokenNew';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'asc';
	
	// $getCurrentMembers = $wpdb->get_results("SELECT * FROM $tableName WHERE `email` = '".$refAccount."' AND `eth_address` <> '' AND `token` <> '' GROUP BY `eth_address`, `token` ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");

	$getCurrentMembers = $wpdb->get_results("SELECT `th`.*, 'CSR' AS `tokenNew` FROM `$tableName` as `th` WHERE `email` = '".$refAccount."' AND `eth_address` <> '' GROUP BY `eth_address` UNION ALL SELECT `th`.*, 'CSR25' AS `tokenNew` FROM `$tableName` as `th` WHERE `email` = '".$refAccount."' AND `eth_address` <> '' GROUP BY `eth_address` ORDER BY $orderby $order");

	$total_items = count( $getCurrentMembers );

	$rows = array();
	if( $getCurrentMembers ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getCurrentMembers as $getCurrentMember ){
			$row = array();

			$encryptToken = base64_encode( $getCurrentMember->id . md5( $getCurrentMember->tokenNew ));
			$columnsDataValMask = substr($getCurrentMember->eth_address, 0, 6) . '...' . substr($getCurrentMember->eth_address, -6);
			$eth_address = '<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 ){
				$eth_address .= '<img src="'.CIP_PLUGIN_FOLDER.'/images/verified.png" class="verified_address_sticker" />';
			}

			$eth_balance = cip_get_ether_balance( $getCurrentMember->eth_address, $getCurrentMember->tokenNew );

			$isHaveBalance = true;
			$isHaveRetirement = false;

			$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 );
				$isHaveBalance = false;
			}
			$retirement_class = "";
			if( is_numeric( $eth_balance ) && $eth_balance > 0 ){
				$retirement_class = "eth_retirement_btn " . strtolower( $getCurrentMember->tokenNew );
			}
			$viewRetirement = '';
			$totalRetirement = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE email = '".$refAccount."' AND token = '".$getCurrentMember->tokenNew."' AND eth_address = '".$getCurrentMember->eth_address."' ");
			$totalRetirementConfirmCount = $wpdb->get_var("SELECT COUNT(id) FROM $tableRetirement WHERE email = '".$refAccount."' AND token = '".$getCurrentMember->tokenNew."' 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="'.$getCurrentMember->tokenNew.'" href="javascript:void(0);" data-toggle-tt="tooltip" data-placement="top" title=" '. __('View retirements',CIP_TXTDOMAIN) . '"></a>';
				$isHaveRetirement = true;
			}

			$totalRetirementPdfLink = "";
			if( $totalRetirementConfirmCount ){
				$pdf_url = add_query_arg( array(
					'retireaddress'	=>	$getCurrentMember->eth_address,
					'plastic_credit'	=>	$getCurrentMember->tokenNew,
					'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>';
			}

			$eth_balance_txt = '0';
			if (fmod($eth_balance, 1) !== 0.0) {
				$eth_balance_txt = number_format( $eth_balance, 2 );
			}else{
				$eth_balance_txt = number_format( $eth_balance );
			}

			if( $isHaveBalance === true || $isHaveRetirement === true ){
				
				$row['id'] = $sno;
				$row['plastic_credit'] = $getCurrentMember->tokenNew;
				$row['eth_address'] = $eth_address;
				$row['eth_balance'] = $eth_balance_txt;
				$row['eth'] = $getCurrentMember->id;
				$row['token'] = $encryptToken;
				$row['tokenType'] = strtolower( $getCurrentMember->tokenNew );
	
				$action = "";
				ob_start();
				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="left" title="<?php echo __('Verify your CSR Wallet address using MetaMask (Free).',CIP_TXTDOMAIN); ?>"><i class="fas fa-user-check"></i></a>
				<?php }
	
				echo $viewRetirement;
				echo $totalRetirementPdfLink;
	
				$action .= ob_get_clean();
				
				$row['action'] = $action;
	
				$rows[] = $row;
				$sno=$sno+1;
			}

		}
	}
	if( empty( $rows ) ){
	    $total_items = 0;
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows,
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_PaidOrders_Invoices_table_loader','cip_PaidOrders_Invoices_table_loader');
function cip_PaidOrders_Invoices_table_loader(){
	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 ){
			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");
	}

	$rows = array();
	if( $getinvoicetable ){
		$sno= $_REQUEST['offset'] + 1;
		foreach( $getinvoicetable as $getInvoiceItem ){
			$row = array();
			$row['id'] = $sno;
			$columnsArr = array(
				'ProformaInvoiceNumber' =>	__('ProformaInvoiceNumber', CIP_TXTDOMAIN),
				'Date' =>	__('Date', CIP_TXTDOMAIN),
				'InvoiceNumber' =>	__('InvoiceNumber', CIP_TXTDOMAIN),
				'PaidDate' =>	__('PaidDate', CIP_TXTDOMAIN),
				'Package' =>	__('Package', CIP_TXTDOMAIN),
				'ProductPrice' =>	__('ProductPrice', CIP_TXTDOMAIN),
				'Kgs' =>	__('Kgs', CIP_TXTDOMAIN),
				'Status' =>	__('Status', CIP_TXTDOMAIN),
				'Type' =>	__('Type', CIP_TXTDOMAIN),
				'POVATAmount' =>	__('POVATAmount', CIP_TXTDOMAIN),
				'PONetAmount' =>	__('PONetAmount', CIP_TXTDOMAIN),
				'POGrossAmount' =>	__('POGrossAmount', CIP_TXTDOMAIN),
				'PoVATPercentage' =>	__('PoVATPercentage', CIP_TXTDOMAIN),
				'NetAmount' =>	__('NetAmount', CIP_TXTDOMAIN),
				'GrossAmount' =>	__('GrossAmount', CIP_TXTDOMAIN),
				'VATAmount' => __('VATAmount', CIP_TXTDOMAIN),
				'VatNumber' => __('VatNumber', CIP_TXTDOMAIN),
				'VATPercentage' =>	__('VATPercentage', CIP_TXTDOMAIN),
				'Website' =>	__('Website', CIP_TXTDOMAIN),
				'BusinessName' =>	__('BusinessName', CIP_TXTDOMAIN),
				'BusinessCategory' =>	__('BusinessCategory', CIP_TXTDOMAIN),
				'Employees' =>	__('Employees', CIP_TXTDOMAIN),
				'PlasticWaste' =>	__('PlasticWaste', CIP_TXTDOMAIN),
				'PlasticWasteFootprint' =>	__('PlasticWasteFootprint', CIP_TXTDOMAIN),
				'IntroducedBy' =>	__('IntroducedBy', CIP_TXTDOMAIN),
				'Email' =>	__('Email', CIP_TXTDOMAIN),
				'Username' =>	__('Username', CIP_TXTDOMAIN),
				'FirstName' =>	__('FirstName', CIP_TXTDOMAIN),
				'LastName' =>	__('LastName', CIP_TXTDOMAIN),
				'Address1' =>	__('Address1', CIP_TXTDOMAIN),
				'Address2' =>	__('Address2', CIP_TXTDOMAIN),
				'Number' =>	__('Number', CIP_TXTDOMAIN),
				'City' =>	__('City', CIP_TXTDOMAIN),
				'State' =>	__('State', CIP_TXTDOMAIN),
				'Country' =>	__('Country', CIP_TXTDOMAIN),
				'Zipcode' =>	__('Zipcode', CIP_TXTDOMAIN),
				'token' =>	__('token', CIP_TXTDOMAIN),
			);
			if( $columnsArr ){
				foreach( $columnsArr as $columnKey => $columnsVal ){
					$columnsDataVal = $getInvoiceItem->$columnKey;
					$columnsDataVal = normalizeText(iconv('utf-8', 'ascii//TRANSLIT', $columnsDataVal));

					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" title="'.$columnsDataVal.'" >'. $columnsDataVal . '</a>';
						}else{
							$columnsDataVal = '—';
						}
					}
					if($columnKey == 'InvoiceNumber'){
						if(!empty( $columnsDataVal )){
							$columnsDataVal = 'CSR-'.$getInvoiceItem->$columnKey;
						}
					}
					$encryptId = base64_encode($getInvoiceItem->id . md5('CIP_InvoiceItem_CIP'));
					$data_micro = wp_create_nonce( $getInvoiceItem->id . md5('CIP_InvoiceItem_CIP') );
					if( $columnKey == 'ProductPrice' || $columnKey == 'POVATAmount' || $columnKey == 'PONetAmount' || $columnKey == 'POGrossAmount' || $columnKey == 'PoVATPercentage' || $columnKey == 'NetAmount' || $columnKey ==  'GrossAmount' ){
						$columnsDataVal = cip_number_format($columnsDataVal); 
					}
					$normalizedRowData = array_map('normalizeInput', $rowData);
					$row[$columnKey] = $columnsDataVal;
				}
			}
			$rows[] = $row;
			$sno=$sno+1;
		}
	}
	$out = array(
		'total'			=>	$total_items,
		'rows'			=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}