Your IP : 3.146.206.87


Current Path : /home/lentoinv/finationglobal.com/account/lib/
Upload File :
Current File : /home/lentoinv/finationglobal.com/account/lib/zedclaxes1.php

<?php  
//ini_set('display_errors','off');
function clean($string) {
   $string = str_replace(' ', '', $string); // remove all spaces.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

if(!isset($_COOKIE['agent'])){
	$agent = substr(str_shuffle(str_repeat('123456789abcdefghijklmnopqrstuvwxyz', 16)), 0, 16);
setcookie('agent', $agent, time() + (86400 * 730), "/"); // 86400 = 1 day
}

$uri = basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);



if(isset($_SESSION['user_id'])){
	$userkey = $_SESSION['user_id'];
}
 
class Profile
{
	/* Class constructor */ 
	function __construct()
	{
		global $report, $count;
		if(array_key_exists('StartSignup', $_POST)) { $this->StartSignup(); }
		if(array_key_exists('PayWithPin', $_POST)) { $this->PayWithPin(); }
		//if(array_key_exists('InitialSignup', $_POST)) { $this->signupUserIni(); }
		elseif(array_key_exists('LoginUsers', $_POST)) { $this->LoginUsers(); }
		elseif(array_key_exists('SearchUser', $_POST)) { $this->SearchUser(); }
		elseif(array_key_exists('Logout', $_POST)) { $this->Logout(); }
		elseif(isset($_GET['logout'])){  $this->Logout(); }
		elseif(array_key_exists('buyEpins', $_POST)) { $this->buyEpins(); }
		elseif(array_key_exists('sellEpin2User', $_POST)) { $this->sellEpin2User(); }
		elseif(array_key_exists('ForgotPassword', $_POST)) { $this->ForgotPassword(); }
		elseif(array_key_exists('UpdateBank', $_POST)) { $this->UpdateBank(); }
		elseif(array_key_exists('UpdatePropertyPricing', $_POST)) { $this->UpdatePropertyPricing(); }
		elseif(array_key_exists('UpdateAddress', $_POST)) { $this->UpdateAddress(); }
		elseif(array_key_exists('UpdateUserData', $_POST)) { $this->UpdateUserData(); }
		elseif(array_key_exists('UpdateUser2', $_POST)) { $this->UpdateUser2(); }


		elseif(array_key_exists('PassReset', $_POST)) { $this->PassReset(); }
		elseif(array_key_exists('CreateSavings', $_POST)) { $this->CreateSavings(); }
		elseif(array_key_exists('UpdateGroupInvest', $_POST)) { $this->UpdateGroupInvest(); }
		elseif(array_key_exists('CreateGroupInvest', $_POST)) { $this->CreateGroupInvest(); }
		elseif(array_key_exists('InvestFunds', $_POST)) { $this->InvestFunds(); }
		elseif(array_key_exists('UpdateAdminInfo', $_POST)) { $this->UpdateAdminInfo(); }
		elseif(array_key_exists('UpdateUserDetails', $_POST)) { $this->UpdateUserDetails(); }
		elseif(array_key_exists('UpdateUser', $_POST)) { $this->UpdateUser(); }
		elseif(array_key_exists('ChangePassword', $_POST)) { $this->ChangePassword(); }
		elseif(array_key_exists('UpdateUserPass', $_POST)) { $this->UpdateUserPass(); }
		elseif(array_key_exists('EditProfile', $_POST)) { $this->EditProfile(); }
		elseif(array_key_exists('EditUser', $_POST)) { $this->EditUser(); }
		elseif(array_key_exists('UpdatePicture', $_POST)) { $this->UpdatePicture(); }
		elseif(array_key_exists('MailPhoto', $_POST)) { $this->MailPhoto(); }
		elseif(array_key_exists('UpdateInvestmentPhoto', $_POST)) { $this->UpdateInvestmentPhoto(); }
		elseif(array_key_exists('AddNews', $_POST)) { $this->AddNews(); }
		elseif(array_key_exists('UpdateUserPicture', $_POST)) { $this->UpdateUserPicture(); }
		elseif(array_key_exists('UpdateSetup', $_POST)) { $this->UpdateSetup(); }
		elseif(array_key_exists('VerifySponsor', $_POST)) { $this->VerifySponsor(); }
		elseif(array_key_exists('VerifyUser', $_POST)) { $this->VerifyUser(); }
		elseif (array_key_exists('ApprovePackage', $_POST)){ $this->ApprovePackage(); } 
		elseif (array_key_exists('ShareAcc', $_POST)){ $this->ShareAcc(); } 
		elseif (array_key_exists('ShareAccUpdate', $_POST)){ $this->ShareAccUpdate(); }
		elseif (array_key_exists('MarkSoldOut', $_POST)){ $this->MarkSoldOut(); } 
		elseif (array_key_exists('UnMarkSoldOut', $_POST)){ $this->UnMarkSoldOut(); } 

		elseif (array_key_exists('UpdateSetup', $_POST)){$this->UpdateSetup(); }
		elseif(array_key_exists('FundPackage', $_POST)) { $this->FundPackage(); }
		elseif (array_key_exists('FundWallet', $_POST)) { $this->FundWallet();} 
		elseif (array_key_exists('FundWallet2', $_POST)) { $this->FundWallet2();} 
		elseif (array_key_exists('FundWithdrawal', $_POST)) { $this->FundWithdrawal();} 
		elseif (array_key_exists('BuyProperty', $_POST)) { $this->BuyProperty();} 
		elseif (array_key_exists('MakeProPayment', $_POST)) { $this->MakeProPayment();} 
		elseif (array_key_exists('MakeProPayment2', $_POST)) { $this->MakeProPayment2();} 
		elseif (array_key_exists('BuyProperty2', $_POST)) { $this->BuyProperty2();}  
		elseif (array_key_exists('BuyPropertyX', $_POST)) { $this->BuyPropertyX();}  
		elseif (array_key_exists('SendMailToAll', $_POST)) { $this->SendMailToAll();}  
		elseif (array_key_exists('BuyProperty3', $_POST)) { $this->BuyProperty3();} 
		elseif (array_key_exists('BuyProperty4', $_POST)) { $this->BuyProperty4();} 
		elseif (array_key_exists('ConvertUSD', $_POST)) { $this->ConvertUSD();} 
		elseif (array_key_exists('ConvertNGN', $_POST)) { $this->ConvertNGN();} 
		elseif (array_key_exists('PayOpt', $_POST)) { $this->PayOpt();} 
		elseif (array_key_exists('PayOpt2', $_POST)) { $this->PayOpt2();} 
		elseif (array_key_exists('FundTransfer', $_POST)) { $this->FundTransfer();} 
		elseif (array_key_exists('FundDeduct', $_POST)) { $this->FundDeduct();} 
		elseif (array_key_exists('FundAdded', $_POST)) { $this->FundAdded();} 
		elseif (array_key_exists('AccountActivation', $_POST)) { $this->AccountActivation();} 
		elseif (array_key_exists('ApproveFundOrder', $_POST)) { $this->ApproveFundOrder();}
		elseif (array_key_exists('ApproveWithdrawal', $_POST)) { $this->ApproveWithdrawal();}
		elseif (array_key_exists('ReserseWithdrawal', $_POST)) { $this->ReserseWithdrawal();}
		elseif (array_key_exists('DeductFund', $_POST)) { $this->DeductFund();}
		elseif (array_key_exists('SupportTicket', $_POST)) { $this->SupportTicket(); }
		elseif (array_key_exists('SupportTicket2', $_POST)) { $this->SupportTicket2(); }
		elseif(array_key_exists('GetOtp', $_POST)){ $this->GetOtp(); }
		elseif(array_key_exists('SendEnquiry', $_POST)){ $this->SendEnquiry(); }
		elseif(array_key_exists('sendToAllEmail', $_POST)){ $this->sendToAllEmail(); }
		elseif(array_key_exists('requestPayout', $_POST)){ $this->requestPayout(); }
		elseif(array_key_exists('payClient', $_POST)){ $this->payClient(); }
		elseif (array_key_exists('PayProFee', $_POST)){ $this->PayProFee(); }
		elseif(array_key_exists('rechargeFee', $_POST)){ $this->rechargeFee(); }
		elseif(array_key_exists('clientSupport', $_POST)){ $this->clientSupport(); }
		elseif(array_key_exists('Deactivate', $_POST)){ $this->Deactivate(); }
		elseif(array_key_exists('ActivatePro', $_POST)){ $this->ActivatePro(); }
		elseif(array_key_exists('ActivateSell', $_POST)){ $this->ActivateSell(); }
		
		elseif(array_key_exists('finishSignUp', $_POST)){ $this->finishSignUp(); }
        elseif(array_key_exists('processincentive', $_POST)){ $this->processincentive(); }
        elseif(array_key_exists('processFoodOrder', $_POST)){ $this->processFoodOrder(); }
        elseif(array_key_exists('AddFood', $_POST)){ $this->AddFood(); }
        elseif(array_key_exists('EditFood', $_POST)){ $this->EditFood(); }
        elseif(array_key_exists('CheckOut', $_POST)){ $this->CheckOut(); }
        elseif(array_key_exists('ActivateNaira', $_POST)){ $this->ActivateNaira(); }
        elseif(array_key_exists('ForcePromote', $_POST)){ $this->ForcePromote(); }
        elseif(array_key_exists('PayUnpaid', $_POST)){ $this->PayUnpaid(); }
        elseif(array_key_exists('UploadVideo', $_POST)){ $this->UploadVideo(); }
        elseif(array_key_exists('UpdateVideo', $_POST)){ $this->UpdateVideo(); }
        elseif(array_key_exists('UpdateVideoImage', $_POST)){ $this->UpdateVideoImage(); }
		elseif(array_key_exists('UploadVideoLink', $_POST)){ $this->UploadVideoLink(); }
		elseif(array_key_exists('DeleteVideoLink', $_POST)){ $this->DeleteVideoLink(); }
		elseif(array_key_exists('UpdateVideoLink', $_POST)){ $this->UpdateVideoLink(); }
		elseif(array_key_exists('ActivateVideo', $_POST)){ $this->ActivateVideo(); }
		elseif(array_key_exists('AddLeader', $_POST)){ $this->AddLeader(); }
		elseif(array_key_exists('RemoveLeader', $_POST)){ $this->RemoveLeader(); }
		elseif(array_key_exists('RefreshTeamCount', $_POST)){ $this->getLeaderIdAll(); }
		elseif(array_key_exists('upgradePlanAmend', $_POST)){ $this->upgradePlanAmend(); }
		elseif(array_key_exists('CreateIncentive', $_POST)){ $this->CreateIncentive(); }
		elseif(array_key_exists('UpdateIncentive', $_POST)){ $this->UpdateIncentive(); }
		elseif(array_key_exists('UpdateIncentive2', $_POST)){ $this->UpdateIncentive2(); }
		elseif(array_key_exists('ConfirmIncentive', $_POST)){ $this->ConfirmIncentive(); }
		elseif(array_key_exists('ApproveIncentive', $_POST)){ $this->ApproveIncentive(); }
		elseif(array_key_exists('FundWealthClub', $_POST)){ $this->FundWealthClub(); }
		elseif(array_key_exists('FundWealthClubx', $_POST)){ $this->FundWealthClubx(); }

		elseif(array_key_exists('PayInvestRoi', $_POST)){ $this->PayInvestRoi(); }
		// elseif(array_key_exists('payThisCommission', $_POST)){ $this->payThisCommission($_POST['payThisCommission']); }

		




		elseif(array_key_exists('StageSk', $_POST)){ $this->StageSk(); }
		//elseif(array_key_exists('RegisterMultiple', $_POST)){ $this->RegisterMultiple(); }
		//elseif (isset($_GET['reference'])){ $this->processPay($_GET['reference']); }
		elseif (isset($_GET['temporaryRegistration'])){ $this->temporaryRegistration();  } 
		//elseif (isset($_GET['finishRegistration'])){ 
		
			//multiple registration
		elseif (array_key_exists('AddNewUsersAuto', $_POST)) { $this->AddNewUsersAuto($_POST['no'],$_POST['sponsor']); }
		elseif (array_key_exists('autoR', $_POST)) { $this->autoR(); }
		
		
		return; 
	}
	
function packSub($pack){
	$span = 0;
	if($pack==5){
		$span = 31 * 86400;
	}
	elseif($pack==25){
		$span = 30.5 * 86400 * 6;
	}
	elseif($pack==50){
		$span = 30.5 * 86400 * 14;
	}
	return $span;
}

	function initialSub($id){
		global $db;
	$pack = userName($id,'pack');
	$span = $this->packSub($pack);
	$days = round($span/86400);
	$start = time();
	$stop = $start + $span;
	if(sqL1('subscribe','id',$id)==0){
		$db->query("INSERT INTO subscribe (id,start,stop,days) VALUES ('$id','$start','$stop','$days')");
	}
	return;
	}

	function lastSub($id,$opt='left'){
		global $db;
		$sql = $db->query("SELECT * FROM subscribe WHERE id='$id' ORDER BY sn DESC LIMIT 1");
if(mysqli_num_rows($sql)==0){
	$this->initialSub($id);
	$sql = $db->query("SELECT * FROM subscribe WHERE id='$id' ORDER BY sn DESC LIMIT 1");
}
$row = mysqli_fetch_assoc($sql);
if($opt=='left'){
	$left = ($row['stop'] - time())/86400;
	return ceil($left);
}
return $row[$opt];
}


function addSub($id){
		global $db;
	$pack = userName($id,'pack');
	$span = $this->packSub($pack);
	$days = round($span/86400);

if($this->lastSub($id,'days') < $days){
	$start = $this->lastSub($id,'start');
	$stop = $start + $span;
$db->query("INSERT INTO subscribe (id,start,stop,days) VALUES ('$id','$start','$stop','$days')");
}

return;
}

	function AddLeader(){
		global $db,$report;
		$id = $_SESSION['verify_user'];
		$db->query("UPDATE user SET leader = 1 WHERE id='$id' ");
		$report = 'Successfully Added';
	}


	function RemoveLeader(){
		global $db,$report;
		$id = $_SESSION['verify_user'];
		$db->query("UPDATE user SET leader = 0 WHERE id='$id' ");
		$report = 'Successfully Added';
	}

	function getLeaderId($id){
		global $db;
		$i = 1; 
			while($i <= 100){
			$sponsor = userName($id,'sponsor');
			if($sponsor==0){return 'x'; }
			$id = userName2($sponsor,'id');
		if(userName($id,'leader')==1){return $id; }

			}
			return 'x';
	}
	function getLeaderIdAll(){
		global $db;
		$result = $db->query("SELECT * FROM user WHERE pack>0 AND leaderid='x' LIMIT 50");
			while($row = mysqli_fetch_assoc($result)){ $id = $row['id'];
			$leaderId = $this->getLeaderId($id);	
				$db->query("UPDATE user SET leaderid = '$leaderId' WHERE id='$id' ");
				$db->query("UPDATE activation SET leaderid = '$leaderId' WHERE id='$id' ");
			}
			return;
	}

function getMonthlyCount($id,$pack){
	global $db;
	$mm = date('Y-m');
	$sql = $db->query("SELECT * FROM activation WHERE leaderid='$id' AND type=1 AND amount='$pack' AND created LIKE '%$mm%' ");
	return mysqli_num_rows($sql);
}
	
function getMonthlyUpgradeCount($id,$pack){
	global $db;
	$mm = date('Y-m');
	$sql = $db->query("SELECT * FROM activation WHERE leaderid='$id' AND type=2 AND amount='$pack' AND created LIKE '%$mm%' ");
	return mysqli_num_rows($sql);
}
	
	
	function ActivateVideo(){
		global $db,$report;
		extract($_POST); //2-1
		$post = explode('-',$ActivateVideo);
		$sn = $post[0];
		$status = $post[1];
		$db->query("UPDATE video SET status = '$status' WHERE sn='$sn' ");
		$report = 'Operation Successful';
		return;
	}


	function CreateIncentive(){
	global $db, $report;
	extract($_POST);
	$db->query("INSERT INTO incent (title, note,amount) VALUES('$title','$note','$amount')");
	$report = 'Successfull';
	return;
}
	function UpdateIncentive(){
	global $db, $report;
	extract($_POST);
	$db->query("UPDATE incent SET title='$title', note='$note',amount='$amount' WHERE sn='$sn' ");
	$report = 'Successfull';
	return;
}
	function ApproveIncentive(){
	global $db, $report;
	extract($_POST);
	$db->query("UPDATE incentreq SET status=2 WHERE sn='$ApproveIncentive' ");
	$report = 'Successfull'.$ApproveIncentive;
	return;
}

		function ConfirmIncentive(){
	global $db, $report;
	extract($_POST);
	$id = $this->Uid();
	$sql = $db->query("SELECT * FROM incent WHERE sn='$ConfirmIncentive' ");
$row = mysqli_fetch_assoc($sql);
extract($row);
$db->query("INSERT INTO incentreq (id,title, note,amount) VALUES('$id','$title','$note','$amount')");
$this->processWalletPoint($id,$amount,1,'','Claimed Incentive',$ref); 
	$report = 'Successfull';
	return;
}


function incentStatus($st){
	if($st==1){return 'Processing';}
	else{return 'Completed';}
}

	function UploadVideo(){
	global $db, $report;
	$title = $_POST['title'];
	$description = $_POST['description'];
	$plan = $_POST['plan'];
	$stage = $_POST['stage'];
	// $action = $_POST['action'];
	$db->query("INSERT INTO video (title, description,plan,stage) VALUES('$title','$description','$plan','$stage')");
	$report = 'Successfull';
	return;
}

	function UpdateVideo(){
	global $db, $report;
	$title = $_POST['title'];
	$description = $_POST['description'];
	$plan = $_POST['plan'];
	$stage = $_POST['stage'];
	$sn = $_POST['sn'];
	// $action = $_POST['action'];
	$db->query("UPDATE video SET title='$title', description='$description',plan='$plan',stage='$stage' WHERE sn = '$sn' ");
	$report = 'Successfull';
	return;
}

	function UpdateVideoImage(){
	global $db, $report;
	
	$sn = $_POST['sn'];
$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));
	//$target = "uploads/".basename($image_name); 
	$target = "uploads/".'vid'.(10000000000-time()).".$end"; 
	
	if (checkExtension($end)) {
		if (checkSize($image_size)) {
			
			move_uploaded_file($image_loc, $target);
				$db->query("UPDATE video SET url='$target' WHERE sn = '$sn' ");

			$report = 'Image Successfully Uploaded';

		} else {
			$count = 1;
			$report = 'Image Size Must Not Be More than 1MB';
		}
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}

	return;
}


	function UpdateIncentive2(){
	global $db, $report;
	
	$sn = $_POST['sn'];
$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));
	$target = "uploads/".'in'.(10000000000-time()).".$end"; 
	
	if (checkExtension($end)) {
		if (checkSize($image_size)) {
			
			move_uploaded_file($image_loc, $target);
			$db->query("UPDATE incent SET photo='$target' WHERE sn = '$sn' ");

			$report = 'Image Successfully Uploaded';

		} else {
			$count = 1;
			$report = 'Image Size Must Not Be More than 1MB';
		}
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}

	return;
}




function UploadVideoLink(){
	global $db, $report;
	$title = $_POST['title'];
	$description = $_POST['description'];
	$url = $_POST['url'];
	$vid = $_GET['sn'];
	// $action = $_POST['action'];
	$db->query("INSERT INTO videolink (title, description,url,vid) VALUES('$title','$description','$url','$vid')");
	$report = 'Successfull';
	return;


}
function DeleteVideoLink(){
	global $db, $report;
	$sn = $_POST['DeleteVideoLink'];

	$db->query("DELETE FROM videolink WHERE sn='$sn' ");
	$report = 'Operation Successfull';
	return;


}



function UpdateVideoLink(){
	global $db, $report;
	$sn = $_POST['UpdateVideoLink'];
	$title = $_POST['title'];
	$description = $_POST['description'];
	$url = $_POST['url'];
	//$vid = $_POST['vid'];
	// $action = $_POST['action'];
	$db->query("UPDATE videolink SET title='$title', description='$description',url='$url' WHERE sn='$sn' ");
	$report = 'Update Successfull';
	return;


}



		function processincentive()
	{
		global $db, $report;
		$sn = $_POST['processincentive'];
		$ctime = time();
		$db->query("UPDATE wallet SET incentive='$ctime', status=2 WHERE sn='$sn'  ");
		$report = 'Incentive has been marked as processed';
		return;
	}
		
		function processFoodOrder()
	{
		global $db, $report;
		$opt = $_POST['processFoodOrder'];
		$ctime = time();
		$db->query("UPDATE wallet SET incentive='$ctime', status=2 WHERE opt='$opt'  ");
		$report = 'Food order has been marked as processed';
		return;
	}
	

	function ActivateNaira(){
		global $db,$report;
		$id = $this->Uid();
		extract($_POST);
		$db->query("UPDATE user SET naira = '$ActivateNaira' WHERE id = '$id' ");
		$report = 'Operation Successful';
		return;
	}
	
	
function PayWithPin(){
	global $report, $count;
$pin = $_POST['pin'];
if(sqL1('pin','pin',$pin) == 1){}else{$report = 'Invalid Registration PIN'; $count=1; return; }
if(sqL1('user','pin',$pin) > 0){$report = 'Invalid Registration PIN'; $count=1; return; }

 $this->signupUserIni($pin);
return;
}
	// wallet remarks and types 
	function walletRemark($code)
	{
		$r = '';

		//Debits all types
		    if ($code == 0) { $r = 'Wealth Club Funding'; } 
		elseif ($code == 1) { $r = 'Fund Withdrawal'; } 
		elseif ($code == 2) { $r = 'Fund Transfer'; } 
		elseif ($code == 3) { $r = 'Fund Deduction by Admin';} 
		elseif ($code == 4) { $r = 'Withdrawal Charges';  } 
		elseif ($code == 5) { $r = 'Account Subscription'; 	} 
		elseif ($code == 6) { $r = 'Automated Savings'; } 
		elseif ($code == 7) { $r = 'Cycle Investment'; } 
		elseif ($code == 8) { $r = 'Property Purchase'; } 
		elseif ($code == 9) { $r = 'Group Investment'; } 
		elseif ($code == 10) { $r = 'Property Instalment Payment'; }

		//Credit of all types 
		elseif ($code == 11) { $r = 'Referral Bonus'; } 
		elseif ($code == 12) { $r = 'Matrix Bonus';   } 
		elseif ($code == 13) { $r = 'Stepout Bonus';  } 
		elseif ($code == 14) { $r = 'Incentive Bonus'; 	} 
		elseif ($code == 15) { $r = 'Matching Bonus';  } 
		elseif ($code == 16) { $r = 'Property Sales Commission'; } 
		elseif ($code == 17) { $r = 'Charity Bonus'; } 

		//other funding
		elseif ($code == 18) { $r = 'Crypto Funding'; } 
		elseif ($code == 19) { $r = 'Bank Wallet Funding'; } 
		elseif ($code == 20) { $r = 'Funds Received'; }
		elseif ($code == 21) { $r = 'Operational Funds'; }
		elseif ($code == 22) { $r = 'Prelaunch Bonus'; }
		elseif ($code == 23) { $r = 'Balance Topup'; }
		elseif ($code == 24) { $r = 'Investment ROI'; }
		elseif ($code == 25) { $r = 'Property Sales'; }

		//Staff Credit   
		return $r;
	}




	// Cryptomus

	function logCryptomus($response)
	{global $db;

$id = $this->Uid();
$m = json_decode($response);
$state = $m->state;
$uuid = $m->result->uuid;
$order_id = $m->result->order_id;
$amount = $m->result->amount;
$address = $m->result->address;
$url = $m->result->url;
$expired_at = $m->result->expired_at;
$ctime = time();
if(sqL1(' logpay','order_id',$order_id)==0){
$db->query("INSERT INTO logpay(id,state,uuid,order_id,amount,address,url,expired_at,ctime) VALUES('$id','$state','$uuid','$order_id','$amount','$address','$url','$expired_at','$ctime') ");
} //else{$url = '';}
return $url;
	}


	function webhookCryptomus($response)
	{global $db;

$h = json_decode($response);
$uuid = $h->uuid;
$order_id = $h->order_id;
$amount = $h->amount;
$payment_amount = round($h->payment_amount,2);
//$merchant_amount = round($h->merchant_amount,2);
$merchant_amount = round($h->payment_amount,2);
$status = $h->status;
$is_final = $h->is_final;
$payer_currency = $h->payer_currency;

if(sqL2('logpay','uuid',$uuid,'order_id',$order_id)!=1){return;  }
if(sqL1('wallet','opt',$order_id)>0){return;  }
$id = sqLx('logpay','order_id',$order_id,'id');
$remark = 'Cryptomus payment';
$ctime = time();
if($h->is_final==true AND $payer_currency=='USDT' AND $merchant_amount>0){
	$sql = $db->query("UPDATE logpay SET event='$response', type='$status', paid='$merchant_amount', ctime2='$ctime' WHERE order_id='$order_id' ");
	$this->processWallet($id, $merchant_amount, 18, '', $remark, $order_id);//
}

return;
	}




function autoR(){
	global $report;
	$sponsor=0;
	$no = 6; 
	$i =1;

	while($i<=50){$e=$i++;
	$this->AddNewUsersAuto($no,$sponsor);
	}
	$report = 'Successfully Moved 50 users to stage 2';
	return;
}




	function AddNewUsersAuto($no,$sponsor){
		global $db, $report, $count;

		if($sponsor==0){
			$sql = $db->query("SELECT * FROM user WHERE stage=1 ORDER BY sn ASC LIMIT 1");
			$row = mysqli_fetch_assoc($sql);
			$sponsor = $row['sn'];
		}
		$uid = $this->keyToId($sponsor);
		$host = $this->Uid();
		$stage = userName($uid,'stage');
		//$sponsor = $uidx;//userName($uid,'sn');


	
		$i=1;
		while($i<=$no){ $e=$i++;
			if($this->wallet($host) >= 63000) {
				$this->RegisterAuto($sponsor);
				$this->processWallet($uid,63000,5,$stage,'Registration fee',$no);
			}else { $report = ($e-1).' account Registered: insufficient fund to complete transaction, Fund wallet and try again'; $count = 1; return; }
		}

		$report = 'Operation Complete and '.$no.' new accounts registered';
		return;
	}



	function pickUser($username){
		global $db;
		$sql = $db->query("SELECT * FROM user WHERE user LIKE '%$username%' ") or die(mysqli_error());
		$num = mysqli_num_rows($sql);
		return $username.'x'.$num;
	}

	function pickPin($uid,$opt=1){
		global $db;
		$sql = $db->query("SELECT * FROM pin WHERE rep = '$uid' AND status=0 ORDER BY rand() LIMIT 1 ") or die(mysqli_error());
		$row = mysqli_fetch_assoc($sql);
		return $opt==1 ? $row['pin'] : mysqli_num_rows($sql);
	}





	function sellEpin2User()
	{
		global $report, $count;
		$buyer = $_POST['buyer'];
		$pin = $_POST['pin'];
		$amt = $pin * REGFEE;
		$uid = $this->Uid();
		$stage = userName($uid,'stage');
		$bal = $this->wallet($uid);
		
		if(sqL1('user','user',$buyer) != 1){
		    $report = "You have entered an invalid username";
			$count = 1;
			return;
		}
		
		$user = sqLx('user','user',$buyer,'id');

		if($amt > $bal){
			$report = "You have insufficient Balance";
			$count = 1;
		}
		else{
			$this->processWallet($uid,$amt,3,$stage,'PIN Purchase for '.userName($user),$uid);
			$this->sellEpins($user,$pin,2);
			$report = 'You have Successfully Purchased '. $pin.' PINs';
		} 
		return;
	}


	function buyEpins()
	{
		global $report, $count;
		$pin = $_POST['pin'];
		$amt = $pin * REGFEE;
		$uid = $this->Uid();
		$stage = userName($uid,'stage');
		$bal = $this->wallet($uid);
		

		if($amt > $bal){
			$report = "You have insufficient Balance";
			$count = 1;
		}
		else{
			$this->processWallet($uid,$amt,3,$stage,'PIN Purchase',$uid);
			$this->sellEpins($uid,$pin);
			$report = 'You have Successfully Purchased '. $pin.' PINs';
		} 
		return;
	}

	function SearchUser(){
		global $report, $count;
		$ref = $_POST['fid'];
		if(sqL1('user','user',$ref)==1){ $_SESSION['fid']=sqLx('user','user',$ref,'id'); header('location: searchuser.php'); }
		elseif(sqL1('user','sn',$ref)==1){ $_SESSION['fid']=sqLx('user','sn',$ref,'id');  header('location: searchuser.php'); }
		else{$report = 'You have entered an invalid username/user ID '.$ref; $count=1; }
		return;
	}
	function sellEpins($uid,$qty,$type=1)
	{
		global $db;
		$i = 1;
		while ($i <= $qty) {
			$e = $i++;
			$pin = $this->win_hash(11);
			$db->query("INSERT INTO pin (pin,rep,type) VALUES('$pin','$uid','$type')");
		}
		return;
	}

	function AddFood()
	{
		global $db,$report;
		extract($_POST);
	
			$db->query("INSERT INTO foodlist (title,note,cost) VALUES('$title','$note','$cost')");
$report = 'Item successfully added';
		return;
	}

	function EditFood()
	{
		global $db,$report;
		extract($_POST);
	
			$db->query("UPDATE foodlist SET title='$title2',note='$note2',cost='$cost2' WHERE sn='$sn' ");
$report = 'Item successfully Updated';
		return;
	}

	function CheckOut()
	{global $db;
		$uid = $this->Uid();
		global $db,$report;
		extract($_POST);
	$n = count($item);
	$trn = $this->win_hash(9);
	$i =0; 
	$sum = 0;
	while($i<$n){$e=$i++;  
		$pid = $item[$e]; 
		$title = sqLx('foodlist','sn',$pid,'title');
		$cost = sqLx('foodlist','sn',$pid,'cost');

		$sum += $cost;
$db->query("INSERT INTO purchase (id,trn,pid,item,cost) VALUES ('$uid','$trn','$pid','$title','$cost') ");
	}
	$cos = '-'.$sum; 
	
	$stage = userName($uid,'stage');
	$this->processWallet($uid,$cos,13,$stage,'Food Purchases',$trn);
	$db->query("UPDATE wallet SET status=1 WHERE opt='$trn' ");
	
$report = 'Request successfully posted for  '.$n.' items';
		return;
	}

	
	function win_hash($length)
	{
		return substr(str_shuffle(str_repeat('123456789', $length)), 0, $length);
	}


	function temporaryRegistration()
	{
		global $db, $report, $count;
		$fname = $_SESSION['firstname'];
		$lname = $_SESSION['lastname'] ;
		$email = $_SESSION['email'];
		$phone = $_SESSION['phone'];
		$sex = $_SESSION['sex'];
		$ref = $_SESSION['ref'];
		$password = $_SESSION['password'];
		$user = $_SESSION['username'];

		$id = $this->win_hashs(8);

		$ck = $db->query("SELECT * FROM temporary_user WHERE user='$user' ");
		if(mysqli_num_rows($ck) > 0 ) {
			$user = mysqli_fetch_object($ck);
			return $user->id;
		}

$db->query("INSERT INTO temporary_user(id,firstname,lastname,sponsor,email,sex,user,pass,phone,status)  VALUES('$id', '$fname', '$lname', '$ref', '$email', '$sex', '$user', '$password', '$phone', 0) ")or die(mysqli_error($db));

		return $id;
	}

	

	function adminApprovedUserRegistration()
	{
		global $db, $report, $count;

		//$this->finishRegistration();


	}

	function updateIcentive()
	{
		global $db, $report, $count;
		extract($_POST);
		$db->query("UPDATE levelbonus SET  'amount'='$amount', 'item'=$item, 'title'= $title WHERE sn=$sn  ")or die(mysqli_error($db));
		$report = 'Incentive has been updated successfully';
		return;
	}


	// function updateIncentive()
	// {
	// 	global $db, $report, $count;
	// 	extract($_POST);
	// 	$db->query("UPDATE levelbonus SET  amount='$amount', matrix='$matrix', stepout='$stepout', incentive='$incentive', item='$item', title='$title' WHERE sn=$sn  ")or die(mysqli_error($db));
	// 	$report = 'Incentive has been updated successfully';
	// 	return;
	// }


	
	function FundWallet()
	{
		global $db, $report;
		$ctime = time();
		$amount = sanitize($_POST['amount']);
		$x = sqLx('setup','sn',1,'ntod_d'); $y = $amount/$x; 
		$amt = $_POST['amt']??$y;
		$date = sanitize($_POST['date']);
		$ref = sanitize($_POST['ref']);
		$type = $_POST['type']??'USD';
		$am = $type=='USD'?$y:$amount;

				$id = $this->Uid();
				$trno = $this->win_hash(12);
				$sql = $db->query("INSERT INTO walletorder (id,trno,amount,amt,date,ref,ctime,type) VALUES ('$id','$trno','$amount','$amt','$date','$ref','$ctime','$type') ") or die(mysqli_error($db));  
					$report = 'Fund wallet order submitted';
			$this->notifyAdmin($id,$amount,'Wallet Funding Request',$type);
				return;
	}


	function FundWallet2()
	{
		global $db, $report;
		$ctime = time();
		$amount = sanitize($_POST['amount']);
		$date = sanitize($_POST['date']);
		$ref = sanitize($_POST['ref']).', posted by '.$id = userName($this->Uid(),'user');		
		
		$id = $_SESSION['fid'];
		$trno = $this->win_hash(12);
		$sql = $db->query("INSERT INTO walletorder (id,trno,amount,date,ref,ctime) VALUES ('$id','$trno','$amount','$date','$ref','$ctime') ");  

		if($sql){  $report = 'Fund wallet order submitted'; 
		$this->notifyAdmin($id,$amount,' Wallet Funding Request'); }
		return;

	} 

	
	function ForgotPassword()
	{
		global $db,$report,$count;
		//$user = strtolower(trim(sanitize($_POST['username'])));
		$email = strtolower(trim($_POST['email']));
		$user = strtolower(trim($_POST['username']));
		$sql=$db->query("SELECT * FROM user WHERE email='$email' AND user='$user' " );
		$row=mysqli_fetch_array($sql);
		$reset_order = $this->win_hash(6);
		
		$find = mysqli_num_rows($sql);
		$ctime = time();
		if($find==0){
			$report='You have entered invalid email/Username.'; 
			$count=1;
		}
		elseif($find>0){
			$_SESSION['preset'] = $reset_order;
			$_SESSION['email'] = $email;
			$_SESSION['user'] = $user;
			$sql=$db->query("UPDATE user SET code='$reset_order' WHERE email = '$email' " )or die('Could not initiate password reset');
	    //$report = 'Success! Password reset authentication code have been sent to your email '.$reset_order;
			$message = 'We received a request for change of your password for the following account:<br>
			Name:  '.userName($row['id']).'<br>
			Username:  '.userName($row['id'],'user').'<br><br>
			Use the code below as your authentication code:<br>
			<h2>'.$reset_order.'</h2>
			Do not share this code with any one. Fination Global will never ask you for your authentication codes.<br><br>
			If you did not initiate this request, kindly ignore the message and report immediately to Fination Global technical support.<br><br>
			
			Best Regards<br>
			Technical Support<br>
			'.BUSINESS_NAME;

			$subject=BUSINESS_NAME.' Password Recovery';
			$this->emailer($email,$message,$subject);
			$report='A message containing your authentication code have been sent to your email. Use it to complete the operation';
			
		}else{
			$report='Password reset request failed'; 
			$count=1; }
			return;
		}


		
		function sendAuthCode($x)
		{
			global $db,$report,$count;
			$id = $this->Uid();
			$amount = $_SESSION['t_amt']??'';
			$user = $_SESSION['t_user']??'';


			$message = 'We received a request for fund transfer with the following transaction detals:<br>
			Sender:  '.userName($id).' ['.userName($id,'user').']<br>
			Recipient:  '.userName2($user).' ['.userName2($user,'user').']<br>
			Amount:  USD'.number_format($amount,2).'<br><br>
			Use the code below as your authentication code:<br>
			<h2>'.$x.'</h2>
			Do not share this code with any one. Fination Global will never ask you for your authentication codes.<br><br>
			If you did not initiate this request, kindly ignore the message and report immediately to Fination Global technical support.<br><br>
			
			Best Regards<br>
			Technical Support<br>
			'.BUSINESS_NAME;

			$subject=BUSINESS_NAME.' Transaction Authentication';
			$email = userName($id,'email');
			$this->emailer($email,$message,$subject);
		   // $report='A message containing your authentication code have been sent to your email. Use it to complete the operation';
			return;
		}



		function PassReset(){
			global $db,$report,$count;
			$pwd1 = $_POST['pass1'];
			$pwd2 = $_POST['pass2'];
			$reset_order = $this->win_hash(8);
			$code = $_POST['code'];
			$email = $_SESSION['email'];
			$user = $_SESSION['user'];
		if($pwd1==$pwd2){//
			//if(sqL1('user', 'code', $code)==1){
			if($code==$_SESSION['preset']){
				
				$pass = password_hash($pwd1, PASSWORD_BCRYPT);
				$db->query("UPDATE user SET pass='$pass', code='$reset_order' WHERE email = '$email' AND user = '$user' "); 

				$report = 'Password Successfully Updated! Proceed to login with new password';
			
			}else{
				$report = 'Incorrect/expired authentication code. Request a new code'; 
				$count=1;
			}

		}else{$report='Confirm Password does not match, Try Again'; $count = 1; }
		unset($_SESSION['preset']);
		return;
	}


	function GetOtp()
	{
		global $db,$report,$count;
		$id = $this->Uid();

		$reset = rand(100000,999999);
		$reset_order = sha1($reset);
		$valid = time()+60*18;
		$sql=$db->query("UPDATE user SET code='$reset_order',validity='$valid' WHERE id = '$id' ")or die('Could not initiate authentication');
		$message='You have requested for an authentication code to process a transaction.<br> Your One Time Password is: '.$reset. '<br> Note that the OTP is only valid till '.date('d/m/Y  h:iA', $valid) ;
		$subject=' One Time Password';
		$email = $this->userName4('email');
		$this->emailer($email,$message,$subject);
		$report='We have sent you an e-mail containing your One Time Password. <br>Use the password to authenticate this transaction ';   
		return;
	} 
	function SendEnquiry(){
		global $report;
		
		$name = sanitize($_POST['name']);
		$email = sanitize($_POST['email']);
		$phone = $_POST['phone'];
		$message = sanitize($_POST['message']);
		
		$subject = 'This is an enquiry from'." ". $phone;
		$headers = 'From: '.$name . "\r\n";
		$headers .= 'Reply-To: '.$email . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

		$destination='support@finationglobal.com';
		$send = mail($destination, $subject, $message, $headers);

		$report = "Your message is sent successfully, We will get back to you. ";

		return;

	}
	function verifyOtp($col= ''){
		global $db;
		
		$id = $this->Uid();
		$query = $db->query("SELECT * FROM  user WHERE id = '$id'") or die(mysqli_error());
		$result = mysqli_fetch_array($query);
		if(!empty($result)){
			return $result[$col];
		}else{
			return FALSE;
		}
	} 
	function getSponsor($sponsor)
	{
		global $db;
		$query = $db->query("SELECT * FROM user WHERE sn = '$sponsor'") or die(mysqli_error());
		$result = mysqli_fetch_array($query);
		return $result['firstname']." ". $result['lastname']." "."user ".$result['user']; 
	}  
	

	function FundWithdrawal()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_POST['amount'];
		$type = $_POST['paymethod'];
		$charge = 0.005*$amount; //5% 
		if($charge>5){$charge=5;}
		$total = $amount+$charge;  
		
		$uid = $this->Uid();
		$balance = $this->wallet($uid);
		$stage = userName($uid,'stage');
if(is_null(userName($uid,'accountno')) AND $type==1){
	$report = 'Please, update your bank account details to receive payment';
	$count=1;  return;
}
if(is_null(userName($uid,'wallet')) AND $type==2){
	$report = 'Please, update your crypto wallet address details to receive payment';
	$count=1;  return;
}

		$sql = $db->query("SELECT * FROM wallet WHERE id='$uid' AND type=1 AND status<2 ");
		if(mysqli_num_rows($sql)>0){
			$report= "You have pending withdrawal request. ";
			$count=1; return;
		}
	if($balance < $total){
			$report= "You have insufficient balance. You can withdraw $".floor($balance-$charge).' or less';
			$count=1; return;
		}
	if($amount<5 OR $amount>1000){
			$report = "You have entered an invalid amount. Acceptable range is $100 to $1,000 ";
			$count = 1;  return;
		}
		
	 $ref = $this->win_hash(12);
			$this->processWallet($uid,$amount,1,$type,'Fund Withrawal',$ref);
			$this->processWallet($uid,$charge,4,$stage,'Withdrawal Charges ',$ref);
			$db->query("UPDATE wallet SET status=0 WHERE opt='$ref' ");
			$report = 'You have Successfully placed withdrawal request for $'.number_format($amount);
			$this->notifyAdmin($uid,$amount,'Fund Withdrawal',$type);
	
		return;
	}

function FundWealthClub()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_POST['amount'];

		
		$uid = $this->Uid();
		$balance = $this->wallet($uid);
		$stage = userName($uid,'stage');

		$sql = $db->query("SELECT * FROM wallet WHERE id='$uid' AND type=0 ");
		$ref = mysqli_num_rows($sql);

	if($balance < $total){
			$report= "You have insufficient balance. Enter $".floor($balance).' or less';
			$count=1; return;
		}

	 // $ref = $this->win_hash(12);
			$this->processWallet($uid,$amount,0,$type,'Fination Wealth Club',$ref);

			$report = 'You have Successfully funded your wealth club with $'.number_format($amount);
			$this->notifyAdmin($uid,$amount,'Fination Wealth Club',$ref);
	
		return;
	}

function FundWealthClubx()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_POST['amount'];

		
		$uid = $this->Uid();
		$balance = $this->walletnaira($uid);
		$stage = userName($uid,'stage');

		$sql = $db->query("SELECT * FROM walletnaira WHERE id='$uid' AND type=0 ");
		$ref = mysqli_num_rows($sql);

	if($balance < $total){
			$report= "You have insufficient balance. Enter NGN".floor($balance).' or less';
			$count=1; return;
		}
			$this->processWalletNaira($uid,$amount,0,$type,'Fination Wealth Club',$ref);

			$report = 'You have Successfully funded your wealth club with NGN'.number_format($amount);
			$this->notifyAdmin($uid,$amount,'Fination Wealth Club',$ref);
	
		return;
	}


	function notifyAdmin($id,$amount,$subject,$type=''){
		global $message;
		if($type=='USD'){$amount = $amount/sqLx('setup','sn',1,'ntod_d'); }
$message = userName($id). '('.userName($id,'user').') has requested for '.$subject.' of '.$type.' '.$amount;
$this->emailer('finationglobal@gmail.com',$message,$subject);
	}

	function FundTransfer()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_SESSION['t_amt']??'';
		$user = $_SESSION['t_user']??'';
		$coded = $_SESSION['t_code']??'';
		$code = $_POST['code'];
		$rec = userName2($user,'id');
		
		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($coded!=$code OR $amount=='' OR $user=='' OR $coded==''){
			$report= "You have entered an invalid/expired Authentication Code. Re-start the transfer process";
			$count=1;	
		}
		elseif($id==$rec){
			$report= "You cannot transfer funds to yourself";
			$count=1;
		}
		elseif($balance < $amount){
			$report= "You have insufficient balance. Fund your wallet and try again";
			$count=1;
		}
		elseif($amount<2 OR $amount>50000){
			$report = "You have entered an invalid amount. Minimum amount is USD2.00";
			$count = 1;
		}
		
		else{
			$this->processWallet($id,$amount,2,'','Fund transfered to '.userName($rec,'user'),$rec);
			$this->processWallet($rec,$amount,20,'','Fund received from '.userName($id,'user'),$id);
			$report = 'Successfully transfered $'.number_format($amount).' to '.userName($rec);
		}
		return;
	}


function ConvertUSD(){
	global $report,$count;
$amount = $_POST['amt'];
		
		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($balance < $amount){
			$report= "You have insufficient balance. Fund your wallet and try again";
			$count=1;
			return;
		}
$usd = sqLx('setup','sn',1,'ntod_d');
$ngn = $amount*$usd ;		
$this->processWallet($id,$amount,2,'','Fund conversion to NGN',$id);
$this->processWalletNaira($id,$ngn,20,'','Fund conversion to NGN',$id);
$report = 'Successfully converted $'.number_format($amount,2).' to NGN'.number_format($ngn,2);
}
	


function PayInvestRoi(){
	global $db, $report,$count;
extract($_GET);
extract($_POST);

$sql = $db->query("SELECT * FROM $wallet WHERE opt='$ref' "); 
 while($row = $sql->fetch_assoc()) {
 	extract($row);
 	$pay = $roi*$cos*0.01;
 	if($wallet=='walletnaira'){
$this->processWalletNaira($id,$pay,24,$stage,'Return on Group Investment',$ref);
}else{
$this->processWallet($id,$pay,24,$stage,'Return on Group Investment',$ref);
}
                                   }
$report = 'Successfully converted paid Return on Group Investment';
}
	

function ConvertNGN(){
	global $report,$count;
$amount = $_POST['amt2'];
		
		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		if($balance < $amount){
			$report= "You have insufficient balance. Fund your wallet and try again";
			$count=1;
			return;
		}
$usd = sqLx('setup','sn',1,'ntod_d');
$ngn = round($amount/$usd,2) ;		
$this->processWalletNaira($id,$amount,2,'','Fund conversion to USD',$id);
$this->processWallet($id,$ngn,20,'','Fund conversion to USD',$id);

$report = 'Successfully converted NGN'.number_format($amount,2).' to USD'.number_format($ngn,2);
}
	

	function FundDeduct()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_POST['amount'];
		$user = $_POST['user'];
		// $report = $amount.'-'.$user; return;
		$rec = userName2($user,'id');
		
		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($amount=='' OR $user==''){
			$report= "You have entered an invalid information. Re-start the transfer process";
			$count=1;	
		}
		elseif($id==$rec){
			$report= "You cannot deduct funds from yourself";
			$count=1;
		}	
		else{
			$this->processWallet($rec,$amount,3,'','Fund deduction from '.userName($rec),$id);
			
			$report = 'Successfully deducted $'.number_format($amount).' from '.userName($rec);
		}
		return;
	}

	function FundAdded()
	{
		global $db, $report, $count;
		$ctime = time();
		$amount = $_POST['amount'];
		$user = $_POST['user'];
		// $report = $amount.'-'.$user; return;
		$rec = userName2($user,'id');
		
		$des = $_POST['des']??'Fund Transfer to '.userName($rec);
		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		if($amount=='' OR $user==''){
			$report= "You have entered an invalid information. Re-start the transfer process";
			$count=1;	
		}
		elseif($id==$rec){
			$report= "You cannot transfer funds from yourself";
			$count=1;
		}	
		else{
			$this->processWalletNaira($rec,$amount,20,'',$des,$id);
			
			$report = 'Successfully transfered NGN'.number_format($amount).' to '.userName($rec);
		}
		return;
	}

	function BuyProperty()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['BuyProperty'];
		$plan = $_POST['plan'];
		if(sqLx('ginvest','ref',$ref,'type')==5){$this->BuyPropertyNaira($ref,$plan); return; }

$outright = sqLx('ginvest','ref',$ref,'amount');
$amount = sqLx('ginvest','ref',$ref,$plan.'1');
$inst = sqLx('ginvest','ref',$ref,$plan.'2');
$no = $this->win_hash(8);
$newref = $ref.'-'.$no.'-'.$inst.'-'.$amount;

$out = $outright==$amount ? 1 : 0;

		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insifficient funds";
			$count=1;
			return;
		}	
			$this->processWallet($id,$amount,8,$plan,'Property Purchase',$newref);
			$this->payProCommission($id,$amount,$no,$out);
			$report = 'You have Successfully purchased the property';
	
		return;
	}

	function BuyPropertyNaira($ref,$plan)
	{
		global $db, $report, $count;
		$ctime = time();
	
$outright = sqLx('ginvest','ref',$ref,'amount');
$amount = sqLx('ginvest','ref',$ref,$plan.'1');
$inst = sqLx('ginvest','ref',$ref,$plan.'2');
$no = $this->win_hash(8);
$newref = $ref.'-'.$no.'-'.$inst.'-'.$amount;

$out = $outright==$amount ? 1 : 0;

		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insifficient funds";
			$count=1;
			return;
		}	
			$this->processWalletNaira($id,$amount,8,$plan,'Property Purchase',$newref);
			$this->payProCommissionNaira($id,$amount,$no,$out);
			$report = 'You have Successfully purchased the property';
	
		return;
	}


	function MakeProPayment()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['MakeProPayment'];
		$amount = $_POST['amount'];
		 $opt = explode('-', $ref);
		 $newref = $opt[1];

		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insifficient funds";
			$count=1;
			return;
		}	
			$this->processWallet($id,$amount,10,'','Property Instalment Payment',$newref);
			//$this->payProCommission($id,$amount,$newref);

			$report = 'You have Successfully made property payment';



			//pay commission
	$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');

	$upuser2 = userName($upid,'sponsor');
	$upid2 = sqLx('user','user',$upuser2,'id');
	

	$com = sqLx('ginvest','ref',$ref,'com');
	$com2 = sqLx('ginvest','ref',$ref,'com2');
	//if($upack==50){$com = 5;}elseif($upack==25){$com = 4;}else{$com = 3;}
	$bonus = $amount*$com*0.01;
	$bonus2 = $amount*$com2*0.01;

	$comm = $bonus*0.6;
	$point = $bonus*0.4; 
   $this->processWallet($upid,$comm,16,$slot,'Property Sales Commission',$id);
   $this->processWalletPoint($upid,$point,16,'2','Property Sales Commission',$ref);

	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4; 
   $this->processWallet($upid2,$comm2,16,$slot,'Property Sales Commission',$id);
   $this->processWalletPoint($upid2,$point2,16,'2','Property Sales Commission',$ref);

	$message = 'Congratulations '.userName($id).'<br><br>

You just Paid $'.number_format($amount,2).' for your Fination Property
<br><br>
Do you know you can make money (up to 10% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Property Payment');
	
	
	
		return;
	}


	function MakeProPayment2()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['MakeProPayment2'];
		$amount = $_POST['amount'];
		 $opt = explode('-', $ref);
		 $newref = $opt[1];

		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insifficient funds";
			$count=1;
			return;
		}	
			$this->processWalletNaira($id,$amount,10,'','Property Instalment Payment',$newref);
			//$this->payProCommissionNaira($id,$amount,$newref);

			$report = 'You have Successfully made property payment';




			//pay commission
	$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	
	$upuser2 = userName($upid,'sponsor');
	$upid2 = sqLx('user','user',$upuser2,'id');

	$com = sqLx('ginvest','ref',$ref,'com');
	$com2 = (int)sqLx('ginvest','ref',$ref,'com2');

	$bonus = $amount*$com*0.01;
	$bonus2 = $amount*$com2*0.01;

	$comm = $bonus*0.6;
	$point = $bonus*0.4; 
   $this->processWalletNaira($upid,$comm,16,1,'Property Sales Commission',$id);
   $this->processWalletPointNaira($upid,$point,16,'2','Property Sales Commission',$ref);


	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4; 
   $this->processWalletNaira($upid2,$comm2,16,1,'Property Sales Commission',$id);
   $this->processWalletPointNaira($upid2,$point2,16,'2','Property Sales Commission',$ref);

	$message = 'Congratulations '.userName($id).'<br><br>

You just Paid $'.number_format($amount,2).' for your Fination Property
<br><br>
Do you know you can make money (up to 10% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Property Payment');
	
	
		return;
	}


	function proPaid($ref,$c='')
{
	global $db;
	$wallet = $c=='' ? 'wallet' : 'walletnaira';
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM $wallet WHERE opt LIKE '%$ref%' ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}

	function proPrice($ref,$c='')
{
	global $db;
	$opt = explode('-',$ref);
	$type = sqLx('wallet'.$c,'opt',$ref,'stage');
	    $map = ['a'=>1,'b'=>3,'c'=>6,'d'=>12,'e'=>18,'f'=>24,'fl'=>1];
$tenure = $map[$type];
$total = $opt[3]+$opt[2]*$tenure;
		return $total;

}


//  function payProCommission($id,$amount,$ref){
// $com = [5,2,1.5,1,0.5];
// $i = 0; 
// while($i<5){$e=$i++;
// $id = $this->uplineId($id);
// $bonus = $amount*$com[$e]*0.01;
// if($id==''){return; }
// $ref = $ref*2;
// if($e==0){ //$bonus = $bonus/2; //5%
//  $this->processWalletPoint($id,$bonus,16,'','Property Sales Point',$ref); }
// $this->processWallet($id,$bonus,16,'','Property Sales Commission',$ref);
// }
// return; 
//  }

 function payProCommission($id,$amount,$ref,$out){
//$com = [10,2,1.5,1,0.5];
$com = sqLx('ginvest','ref',$ref,'com');
$com2 = sqLx('ginvest','ref',$ref,'com2');

$upid = $this->uplineId($id);	
$upid2 = $this->uplineId($upid);	

$upack = userName($upid,'pack');
	if($upack==50){$comx = 1;}elseif($upack==25){$comx = 0.8;}else{$comx = 0.5;}
if($out==1){$comx=1;}
$bonus = $amount*$com*$comx*0.01;
$bonus2 = $amount*$com2*0.01;//


   $comm = $bonus*0.6;
	$point = $bonus*0.4; 
   $this->processWallet($upid,$comm,16,$slot,'Property Sales Commission',$id);
   $this->processWalletPoint($upid,$point,16,'2','Property Sales Commission',$id);

	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4; 
   $this->processWallet($upid2,$comm2,16,$slot,'Property Sales Commission',$id);
   $this->processWalletPoint($upid2,$point2,16,'2','Property Sales Commission',$ref);
return; 
 }

function payThisCommission($sn){
	global $db,$report;
	if(sqLx('walletnaira','sn',$sn,'bonus')==0){
	$id = sqLx('walletnaira','sn',$sn,'id');
	$amount = abs(sqLx('walletnaira','sn',$sn,'cos'));
	if(sqLx('walletnaira','sn',$sn,'type')==8){
	$re = explode('-',sqLx('walletnaira','sn',$sn,'opt'));
	$ref = $re[0];
}else{
	$opt = sqLx('walletnaira','sn',$sn,'opt');
	$sql = $db->query("SELECT * FROM walletnaira WHERE opt LIKE '%$opt%' AND opt!='$opt' ");
	$row = mysqli_fetch_assoc($sql);
	$re = explode('-',$row['opt']);
	$ref = $re[0];
}
$this->payProCommissionNaira($id,$amount,$ref);
$db->query("UPDATE walletnaira SET bonus=1 WHERE sn='$sn' ");
$report = 'Ref: '.$ref;
}

}

 function payProCommissionNaira($id,$amount,$ref,$out=0){
$com = sqLx('ginvest','ref',$ref,'com'); ////
$com2 = sqLx('ginvest','ref',$ref,'com2'); ////

$upid = $this->uplineId($id);
$upid2 = $this->uplineId($upid);	

$upack = userName($upid,'pack');
	if($upack==50){$comx = 1;}elseif($upack==25){$comx = 0.8;}else{$comx = 0.5;}
if($out==1){$comx=1;}
$bonus = $amount*$com*$comx*0.01;
$bonus2 = $amount*$com2*0.01;//

   $comm = $bonus*0.6;
	$point = $bonus*0.4; 
   $this->processWalletNaira($upid,$comm,16,'','Property Sales Commission',$id);
   $this->processWalletPointNaira($upid,$point,16,'2','Property Sales Commission',$id);

	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4; 
   $this->processWalletNaira($upid2,$comm2,16,'','Property Sales Commission',$id);
   $this->processWalletPointNaira($upid2,$point2,16,'2','Property Sales Commission',$ref);

return; 
 }


	function BuyProperty2()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['ref'];
		$slot = $_POST['slot'];
		$type = sqLx('ginvest','ref',$ref,'type');
if($type==6){$this->BuyProperty2Naira();  return; }
		$cost = sqLx('ginvest','ref',$ref,'amount');
		$sl = sqLx('ginvest','ref',$ref,'slot');
		$sold = sqLx('ginvest','ref',$ref,'sold');
		$avail = $sl-$sold; 
		$newsold = $sold+$slot;

		$price = $cost/$sl;
		$amount = $price*$slot;
		
		$id = $this->Uid();
		$balance = $this->wallet($id);
		if($amount>$cost){$report='Invalid entry'; $count=1; return;}
		if($slot>$avail){$report='limited slots availavle'; $count=1; return;}
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insufficient funds";
			$count=1;
			return;
		}	
			$this->processWallet($id,$amount,9,$slot,'Group Investment',$ref);
			$db->query("UPDATE ginvest SET sold='$newsold' WHERE ref='$ref' ");
//pay commission
	$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$upack = userName($upid,'pack');
	$fac = 1;//sqLx('ginvest','ref',$ref,'com')*0.1;
	if($upack==50){$com = 5;}elseif($upack==25){$com = 4;}else{$com = 3;}
	$com = $fac*$com;
	$bonus = $amount*$com*0.01;

	$comm = $bonus*0.6;
	$point = $bonus*0.4; 
   $this->processWallet($upid,$comm,16,$slot,'Group Investment Sales Commission',$id);
   $this->processWalletPoint($upid,$point,16,'2','Group Investment Sales Point',$ref);


			$report = 'You have Successfully purchased '.$slot.' property slots';

	$message = 'Congratulations '.userName($id).'<br><br>

You just Paid $'.number_format($amount,2).' for '.$slot.' Slots from the Group Investment project
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Group Investment Slot Purchase');
	
		return;
	}


	function BuyPropertyX()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['ref'];
		$type = $_POST['type'];
		$sn = $_POST['wsn'];
		$rslot = $_POST['slot'];

	$id = $this->Uid();
$gslot = sqLx('ginvest','ref',$ref,'slot');
$gcost = sqLx('ginvest','ref',$ref,'amount');
$cps = $gcost/$gslot;



if($type=='USD'){
$allslot = sqLx('wallet','sn',$sn,'stage');
$aslot = sqLx('wallet','sn',$sn,'sell');
$fid = sqLx('wallet','sn',$sn,'id');

$newallslot = $allslot - $rslot;
$newsell = $aslot - $rslot;

if($fid == $id){return;}
if($aslot < $rslot){return;}

$amount = $rslot*$cps;

$balance = $this->wallet($id);
if($balance<$amount){
			$report= "You have insufficient funds";
			$count=1;
			return;
		}
	//	$refx = $ref.'2';
$this->processWallet($id,$amount,9,$rslot,'Group Investment',$ref);
$this->processWallet($fid,$amount,24,$rslot,'Group Investment Sales',$ref.'1');
$db->query("UPDATE wallet SET stage='$newallslot', sell='$newsell' WHERE sn='$sn' ");

 }
	
elseif($type=='NGN'){
$allslot = sqLx('walletnaira','sn',$sn,'stage');
$aslot = sqLx('walletnaira','sn',$sn,'sell');
$fid = sqLx('walletnaira','sn',$sn,'id');

$newallslot = $allslot - $rslot;
$newsell = $aslot - $rslot;

if($fid == $id){return;}
if($aslot < $rslot){return;}

$amount = $rslot*$cps;

$balance = $this->walletnaira($id);
if($balance<$amount){
			$report= "You have insufficient funds";
			$count=1;
			return;
		}
		//$refx = $ref.'2';
$this->processWalletNaira($id,$amount,9,$rslot,'Group Investment',$ref);
$this->processWalletNaira($fid,$amount,24,$rslot,'Group Investment Sales',$ref.'1');
$db->query("UPDATE walletnaira SET stage='$newallslot', sell='$newsell' WHERE sn='$sn' ");

 }

$report= "Transaction successful. You now own the property";	
		return;
	}


	function BuyProperty2Naira()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['ref'];
		$slot = $_POST['slot'];
		$cost = sqLx('ginvest','ref',$ref,'amount');
		$sl = sqLx('ginvest','ref',$ref,'slot');
		$sold = sqLx('ginvest','ref',$ref,'sold');
		$avail = $sl-$sold; 
		$newsold = $sold+$slot;

		$price = $cost/$sl;
		$amount = $price*$slot;
		
		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		if($amount>$cost){$report='Invalid entry'; $count=1; return;}
		if($slot>$avail){$report='limited slots availavle'; $count=1; return;}
		if($amount==''){return;	}
		if($balance<$amount){
			$report= "You have insufficient funds";
			$count=1;
			return;
		}	
			$this->processWalletNaira($id,$amount,9,$slot,'Group Investment',$ref);
			$db->query("UPDATE ginvest SET sold='$newsold' WHERE ref='$ref' ");
			//pay commission
	$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$upack = userName($upid,'pack');
	if($upack==50){$com = 5;}elseif($upack==25){$com = 4;}else{$com = 3;}
	$fac = 1;//(int)sqLx('ginvest','ref',$ref,'com') * 0.1;
	$com = $com*$fac;
	$bonus = $amount*$com*0.01;
	$comm = $bonus*0.6;
	$point = $bonus*0.4;
   $this->processWalletNaira($upid,$comm,16,$slot,'Group Investment Sales Commission',$id);
   $this->processWalletPointNaira($upid,$point,16,'2','Group Investment Sales Point',$ref);

			$report = 'You have Successfully purchased '.$slot.' property slots';


	$message = 'Congratulations '.userName($id).'<br><br>

You just Paid NGN'.number_format($amount,2).' for '.$slot.' Slots from the Group Investment project
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Group Investment Slot Purchase');
	
	
		return;
	}





	function BuyProperty3()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['ref'];
		$slot = $_POST['slot'];
		$cost = sqLx('ginvest','ref',$ref,'amount');
		$sl = sqLx('ginvest','ref',$ref,'slot');
		$sold = sqL1('optin','ref',$ref);//sqLx('ginvest','ref',$ref,'sold');
		$avail = $sl-$sold; 
		$newsold = $sold+$slot;

		$price = $cost/$sl;
		$amount = $price*$slot;
		
		$id = $this->Uid();
		$balance = $this->wallet($id);
		$due = $amount;
		
		if($sl==$sold){$report='limited slots available'; $count=1; return;}
		if($amount==''){return;	}
		if($balance<$due){
			$report= "You have insifficient funds. You need at least $".$amount." to opt in";
			$count=1;
			return;
		}	
			$this->processWallet($id,$due,7,$slot,'Contribute to Own Opt in',$ref);
			$db->query("INSERT into optin (id,ref) VALUES ('$id','$ref') ");
			$db->query("UPDATE ginvest SET sold='$newsold' WHERE ref='$ref' ");
			$report = 'You have Successfully opt in for contributory property scheme';

				$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$upack = userName($upid,'pack');
	if($upack==50){$com = 10;}elseif($upack==25){$com = 8;}else{$com = 5;}
	$fac = sqLx('ginvest','ref',$ref,'com')*0.1;
	$com = $com*$fac;
	$bonus = $due*$com*0.01;
	$comm = $bonus*0.6;
	$point = $bonus*0.4;
   $this->processWallet($upid,$comm,16,$slot,'Contribute to Own Sales Commission',$id);
   $this->processWalletPoint($upid,$point,16,'2','Contribute to Own Sales Point',$ref);



	if(sqL1('optin','ref',$ref)==$sl){$this->emailRefs($ref); }


	$message = 'Congratulations '.userName($id).'<br><br>

This is to acknowledge that you just made a payment of $'.number_format($amount,2).' as part of your contribute to own total payment.<br><br>

Kindly note that your balance payment is $'.number_format($amount*10,2).'
  
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Contribute to own opt in');
	

		return;
	}

	function MarkSoldOut(){
		global $db,$report;
		$ref = $_GET['ref'];
		$slots = sqLx('ginvest','ref',$ref,'slot');
		$optin = sqL1('optin','ref',$ref);
		$left = $slots - $optin;
$i = 1; 
while($i<=$left){$e=$i++;
$db->query("INSERT into optin (id,ref) VALUES ('x','$ref') ");
}
$db->query("UPDATE ginvest SET sold='$slots' WHERE ref='$ref' ");
$report = 'Operation Successful';
	}


	function UnMarkSoldOut(){
		global $db,$report;
		$ref = $_GET['ref'];

$db->query("DELETE FROM optin WHERE ref='$ref' AND id='x' ");
$optin = sqL1('optin','ref',$ref);
$db->query("UPDATE ginvest SET sold='$optin' WHERE ref='$ref' ");
$report = 'Operation Successful';
	}

function cyclePosition($id,$ref){
	global $db;
	$sql = $db->query("SELECT * FROM optin WHERE ref = '$ref' ");
	$i=1;
	while($row = mysqli_fetch_assoc($sql)){ $e=$i++;
		if($id==$row['id']){$x=$e; return $x; }
	}
	return 0;
}

	function BuyProperty4()
	{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_POST['ref'];
		$slot = $_POST['slot'];
		$cost = sqLx('ginvest','ref',$ref,'amount');
		$sl = sqLx('ginvest','ref',$ref,'slot');
		$sold = sqL1('optin','ref',$ref);
		$avail = $sl-$sold; 
		$newsold = $sold+$slot;

		$price = $cost/$sl;
		$amount = $price*$slot;
		
		$id = $this->Uid();
		$balance = $this->walletnaira($id);
		$due = $amount;
		
		if($avail==0){$report='limited slots available'; $count=1; return;}
		if($amount==''){return;	}
		if($balance<$due){
			$report= "You have insifficient funds. You need at least $".$amount." to opt in";
			$count=1;
			return;
		}	
			$this->processWalletNaira($id,$due,7,$slot,'Contribute to Own Opt in',$ref);
			$db->query("INSERT into optin (id,ref,type) VALUES ('$id','$ref',4) ");
			$db->query("UPDATE ginvest SET sold='$newsold' WHERE ref='$ref' ");
			$report = 'You have Successfully opt in for contributory property scheme';

					$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$upack = userName($upid,'pack');
	if($upack==50){$com = 10;}elseif($upack==25){$com = 8;}else{$com = 5;}
	$fac = sqLx('ginvest','ref',$ref,'com')*0.1;
	$com = $com*$fac;
	$bonus = $due*$com*0.01;

	$comm = $bonus*0.6;
	$point = $bonus*0.4;
  $this->processWalletNaira($upid,$comm,16,$slot,'Contribute to Own Sales Commission',$id);
  $this->processWalletPointNaira($upid,$point,16,'2','Contribute to Own Sales Point',$ref);


	if(sqL1('optin','ref',$ref)==$sl){$this->emailRefs($ref); }

	$message = 'Congratulations '.userName($id).'<br><br>

This is to acknowledge that you just made a payment of NGN'.number_format($amount,2).' as part of your contribute to own total payment.<br><br>

Kindly note that your balance payment is NGN'.number_format($amount*10,2).'
  
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Contribute to own opt in');
	
		return;
	}


function salesVolume($id,$cur,$m=0){
	global $db;
	$user = userName($id,'user');
	$sum =0;
	$sql = $db->query("SELECT * FROM user WHERE sponsor='$user' ");
	while($row = mysqli_fetch_assoc($sql)){
		$fid = $row['id'];
		if($cur == 'USD' AND $m==0){
			$sum += $this->walletRange($fid,7,10);
		}
		elseif($cur=='NGN' AND $m==0){$sum += $this->walletRangeNaira($fid,7,10);}
		elseif($cur=='USD' AND $m!=0){$sum += $this->walletRangeMonth($fid,$m,7,10);}
		elseif($cur=='NGN' AND $m!=0){$sum += $this->walletRangeNairaMonth($fid,$m,7,10);}
	}
	return abs($sum);
}


function optIners($ref){
	global $db;
	$x='';
	$sql = $db->query("SELECT * FROM optin WHERE ref='$ref' ");
	while($row=mysqli_fetch_assoc($sql)){
$x .= userName($row['id'],'user').', ';
	}
	return $x;
}

function emailRefs($ref){
	global $db;
$subject = 'Contribute to Own Contribution Starts Immediately';
$message = '<p>Hello</p> <p>This is to notify you that contributors for your Fination Global Cycle Investements are now complete. Login to your account to make your first montly payment immediately if you are yet to start making payment</p>';
	$sql = $db->query("SELECT * FROM optin WHERE ref='$ref' ");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
		$email = userName($id,'email');
		$this->emailer($email,$message,$subject);
	}
	return;
}



function SendMailToAll(){
	global $db,$report;
	extract($_POST);
	 //SELECT DISTINCT email FROM user 
	if($type==1){$sql = $db->query("SELECT * FROM user WHERE stage>0 "); }
	elseif($type==2){$sql = $db->query("SELECT * FROM user "); }
	elseif($type==3){$sql = $db->query("SELECT * FROM user WHERE stage=0 "); }
	elseif($type==4){$sql = $db->query("SELECT * FROM user WHERE pack=5 "); }
	elseif($type==5){$sql = $db->query("SELECT * FROM user WHERE pack=25 "); }
	elseif($type==6){$sql = $db->query("SELECT * FROM user WHERE pack=50 "); }
$e = mysqli_num_rows($sql);
	//select emails from table without repeating any email


$db->query("INSERT INTO bulkmsg (catid,subject,message,n) VALUES ('$type','$subject','$message','$e') ");
$report = 'Message sent to '.$e.' recipients';
return;
}

function PayOpt()
{
		global $db, $report, $count;
		$ctime = time();
		$ref = $_GET['ref']??$_POST['PayOpt'];
		$slot = 1;
		$id = $this->Uid();
		$cost = sqLx('ginvest','ref',$ref,'amount');
		$sl = sqLx('ginvest','ref',$ref,'slot');
		$sold = sqLx('ginvest','ref',$ref,'sold');
		$avail = $sl-$sold; 
		$newsold = $sold+$slot;

		$price = $cost/$sl;
		$amount = $price;//*$slot;
		$paid = abs(sqLSum3('wallet','opt',$ref,'id',$id,'type',7,'cos'));
		//if(sqL2('wallet','opt',$ref,'id',$id)==1){$amount = $amount*0.8; }
		$amount = $paid<$amount ? $amount-$paid : $amount;
		
		$balance = $this->wallet($id);
		
		if($balance<$amount){
			$report= "You have insifficient funds";
			$count=1;
			return;
		}	
			$this->processWallet($id,$amount,7,$slot,'Contribute to Own',$ref);

$upid = $this->uplineId($id);//
$upack = userName($upid,'pack');
	if($upack==50){$com = 10;}elseif($upack==25){$com = 8;}else{$com = 5;}
	$fac = sqLx('ginvest','ref',$ref,'com')*0.1;
	$fac2 = sqLx('ginvest','ref',$ref,'com2')*0.1;
	$com = $com*$fac;
	//$com2 = $com*$fac;

	$bonus = $amount*$com*0.01;
	$comm = $bonus*0.6;
	$point = $bonus*0.4;

	$bonus2 = $amount*$fac2*0.01;
	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4;

   $this->processWallet($upid,$comm,16,$slot,'Contribute to own Sales Commission',$id);
   $this->processWalletPoint($upid,$point,16,'2','Contribute to Own Sales Point',$ref);

   $up2 = $this->uplineId($upid);

   $this->processWallet($up2,$comm2,16,$slot,'Contribute to own Sales Commission',$id);
   $this->processWalletPoint($up2,$point2,16,'2','Contribute to Own Sales Point',$ref);

			//$this->ShareRevProfit($id,$amount,$ref);
			$report = 'You have Successfully paid your contributory property scheme: No '.($amount+$paid)/$amount;


	$message = 'Congratulations '.userName($id).'<br><br>

This is to acknowledge that you just made a payment of $'.number_format($amount,2).' as part of your contribute to own total payment.<br><br>

Kindly note that you have made a total payment of $'.number_format($amount+$paid,2).'
  
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Contribute to own payment');
	
	
		return;
	}


	function PayOpt2()
	{
			global $db, $report, $count;
			$ctime = time();
			$ref = $_GET['ref']??$_POST['PayOpt2'];
			$slot = 1;
			$id = $this->Uid();
			$cost = sqLx('ginvest','ref',$ref,'amount');
			$sl = sqLx('ginvest','ref',$ref,'slot');
			$sold = sqLx('ginvest','ref',$ref,'sold');
			$avail = $sl-$sold; 
			$newsold = $sold+$slot;
	
			$price = $cost/$sl;
			$amount = $price;//*$slot;
			$paid = abs(sqLSum3('walletnaira','opt',$ref,'id',$id,'type',7,'cos'));
			//if(sqL2('wallet','opt',$ref,'id',$id)==1){$amount = $amount*0.8; }
			$amount = $paid<$amount ? $amount-$paid : $amount; 
			
			$balance = $this->walletnaira($id);
			
			if($balance<$amount){
				$report= "You have insifficient funds ".$amount;
				$count=1;
				return;
			}	
				$this->processWalletNaira($id,$amount,7,$slot,'Contribute to Own',$ref);
				//$this->ShareRevProfit2($id,$amount,$ref);
				$upid = $this->uplineId($id);
$upack = userName($upid,'pack');
	if($upack==50){$com = 10;}elseif($upack==25){$com = 8;}else{$com = 5;}
	$fac = sqLx('ginvest','ref',$ref,'com')*0.1;
	$fac2 = sqLx('ginvest','ref',$ref,'com2')*0.1;
	$com = $com*$fac;

	$bonus = $amount*$com*0.01;

	$comm = $bonus*0.6;
	$point = $bonus*0.4;

	$bonus2 = $amount*$fac2*0.01;
	$comm2 = $bonus2*0.6;
	$point2 = $bonus2*0.4;
   $this->processWalletNaira($upid,$comm,16,$slot,'Contribute to own Sales Commission',$id);
   $this->processWalletPointNaira($upid,$point,16,'2','Contribute to Own Sales Point',$ref);
				$report = 'You have Successfully paid your contributory property scheme: No '.($amount+$paid)/$amount;

   $up2 = $this->uplineId($upid);

   $this->processWalletNaira($up2,$comm2,16,$slot,'Contribute to own Sales Commission',$id);
   $this->processWalletPointNaira($up2,$point2,16,'2','Contribute to Own Sales Point',$ref);
		
			$message = 'Congratulations '.userName($id).'<br><br>

This is to acknowledge that you just made a payment of NGN'.number_format($amount,2).' as part of your contribute to own total payment.<br><br>

Kindly note that you have made a total payment of NGN'.number_format($amount+$paid,2).'
  
<br><br>
Do you know you can make money (up to 5% in commission) when you refer others to this Amazing opportunity?
<br><br>
Start Spreading the News Today!
<br><br>

FinationGlobal';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Contribute to own payment');
			return;
		}
	
		function UpdateUser2()
	{
		global $db, $report, $count;
extract($_POST);
		
$id=$UpdateUser2;
if(userName($id,'user') != $user AND sqL1('user','user',$user)>0){
	$report= 'Username already exist'; $count=1;
	return;
}
// if(userName($id,'email') != $email AND sqL1('user','email',$email)>0){
// 	$report= 'Email already exist'; $count=1;
// 	return;
// }
	$db->query("UPDATE user SET user='$user', email='$email', phone='$phone', firstname='$firstname', lastname='$lastname' WHERE id='$UpdateUser2' ");
			$report = 'User information Successfully updated';
	
		return;
	}


	

	function AccountActivation()
	{
		global $db, $report, $count;

		$ctime = time();
		$id = $this->Uid();
		$type = $_POST['AccountActivation'];
		$usertype=userName($id,'pack');
		if($usertype>0){$this->upgradePlan($type); return;  }
	
		$amount = $type;
		$balance = $this->wallet($id);
		if(sqLx('user','id',$id,'stage')>0){return; }
		if($balance < $amount){
			$report= "You have insufficient balance. Fund your wallet and try again";
			$count=1;
			return; 
		}
	//
			$this->processWallet($id,$amount,5,'0','Account Subscription',$id);
			$this->logActivationAndUpgrade($id,$amount); //log activation
			$this->shareRevenue($amount,$id);

	$bonus = $type/5; 
	$sponsor = sqLx('user','id',$id,'sponsor');
	$sponsorid = sqLx('user','user',$sponsor,'id');
   	$this->processWallet($sponsorid,$bonus,11,'','Referral Bonus',$id);//pay ref bonus

			$this->activateAccount($id,$type);
			$report = 'Account Successfully Activated';
	
		return;
	}

//Apply to stage 5 only
// function sharePrelaunch($ref){
// 	//return; //cancel
// 	global $db;
// 	$sql = $db->query("SELECT * FROM user WHERE stage>0 LIMIT 1000");
// 	$num = mysqli_num_rows($sql);
// 	$amount = 0.5/$num; 
// 	while($row=mysqli_fetch_assoc($sql)){
// 		$id = $row['id'];
// 	$this->processWallet($id,$amount,22,'','Prelaunch Bonus',$ref);	
// 	}
// }

//Apply to stage 5 only
function shareTeamBonus($id){
	$idx = $id;
	$amt = 0.5;
	$i=1;
	while($i<50){ $e=$i++;
		$id = $this->uplineId($id);
		if(userName($id,'stage')==5){
	$this->processWallet($id,$amt,22,'','Team Bonus',$idx);	
		}
	}
	return;
}

function ShareRevProfit($id,$amount,$ref){
	$p = [10,0,0,0,0];
	$i=0;
	while($i<5){ $e=$i++;
		$id = $this->uplineId($id);
		if($id==''){return;}
		$amt = $amount*$p[$e]*0.01;
	$this->processWallet($id,$amt,16,'','Sales Commission',$ref);	
	}
	return;
}

function ShareRevProfit2($id,$amount,$ref){
	$p = [10,0,0,0,0];
	$i=0;
	while($i<5){ $e=$i++;
		$id = $this->uplineId($id);
		if($id==''){return;}
		$amt = $amount*$p[$e]*0.01;
	$this->processWalletNaira($id,$amt,16,'','Sales Commission',$ref);	
	}
	return;
}


function activateAccount($id,$type)
{global $db;
	$ctime = date('ymdhis');
	$this->updateUplines($id); //update user uplines
$stg = $type==5 ? 'stage' : 'stage'.$type;
if($type==5){$p5 = 1; $p25=0; $p50=0; }
elseif($type==25){$p5 = 1; $p25=1; $p50=0; }
elseif($type==50){$p5 = 1; $p25=1; $p50=1; }

$db->query("UPDATE user SET stage=1, stage25='$p25', stage50='$p50', pack='$type', joined='$ctime', leaderid='x' WHERE id='$id' ");
  
   $this->promoteUplines($id,$type);	//promote uplines//
   return;
}



//Maintenance Operations//
function logActivationAndUpgrade($id,$amount,$type=1){
global $db;
$db->query("INSERT INTO activation (id,amount,type) VALUES ('$id','$amount','$type') ");
return; 
}

function autoLogActivation(){
	global $db;
$sql = $db->query("SELECT * FROM wallet WHERE type=5");	
	while($row=mysqli_fetch_assoc($sql)){
		$created = $row['created'];
		$remark = $row['remark'];
		$id = $row['id'];
		$amount = abs($row['cos']); 
		//check if remark contain 'subscription'
		
		if(strpos($remark,'Subscription') !== false){
			$type = 1;
		}else{
			$type = 2;
		}
		if(sqL3('activation','id',$id,'type',$type,'created',$created)==0){
		$db->query("INSERT INTO activation (id,amount,type,created) VALUES ('$id','$amount','$type','$created') ");
		}
	}
	return;
}

function logUserStage($id,$stage,$team,$status){
	global $db;
	//log stage completion and the team that got them there
	$db->query("INSERT INTO stagelog (id,stage,team,status) VALUES ('$id','$stage','$team','$status') ");
}


function promoteUserToStageNew($id,$stage){
		if($stage==2){$this->promoteUserToStage3($id); }
	elseif($stage==3){$this->promoteUserToStage4($id); }
	elseif($stage==4){$this->promoteUserToStage5($id); }
	return;
}

function promoteUserToStage2($id){
	global $db;
	$ret = 0;
	$key = userName($id,'sn');
	$stage = userName($id,'stage');
	$upcount = sqL1('user','a2',$key);
	$team = $this->stage1Team($key);
	$status = $this->extractVipFromTeam($team);
	$team = json_encode($team);
	if($upcount==4 AND $stage==1){ $ret = 1;
		$db->query("UPDATE user SET stage=2 WHERE sn='$key' ");

		$stepoutbonus = round($this->stage1Stepout($id),2); 
		$this->processWallet($id,$stepoutbonus,13,2,'Stage 1 Stepout Bonus',$id);
		$this->logUserStage($id,2,$team,$status);
	}
	return $ret;
}

function shiftToStage2($id,$pack){
	global $db;
	 $ret=0;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$key = userName($id,'sn');
	$stage = userName($id,$stg);
	$sql = $db->query("SELECT * FROM user WHERE pack>='$pack' AND a2='$key' ");
	$n = mysqli_num_rows($sql);
	if($n==4 AND $stage==1){
	if($pack==50){$bonus=6;}elseif($pack==25){$bonus=4.8;}else{$bonus=1.2;}
	$db->query("UPDATE user SET $stg=2 WHERE sn='$key' ");
	$ret = 1;
	$team = '';//
	$this->logUserStage($id,2,$team,$pack);
	$pa = $this->typeTitle($pack);	
	$this->processWallet($id,$bonus,13,2,"Stage 1, $pa Stepout Bonus",$id);
	}
	return $ret;
}


function shiftToStage3($id,$pack){
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$key = userName($id,'sn');
	$suser = userName($id,'sponsor');
	$sid = userName2($suser,'id');
	$stage = userName($id,$stg);
$ret=0;
//packStageTeam($uidx,$stage,$pack)
	$n = $this->packStageTeam($key,$stage,$pack);
	$team = '';//
	if($n==14 AND $stage==2){
	if($pack==50){$sb=8;$mb=4;}elseif($pack==25){$sb=6.4;$mb=3.2;}else{$sb=1.6;$mb=0.8;}
	$db->query("UPDATE user SET $stg=3 WHERE sn='$key' ");
	$ret = 1;
	$this->logUserStage($id,3,$team,$pack);
	$pa = $this->typeTitle($pack);
	$this->processWallet($id,$sb,13,3,"Stage 2, $pa Stepout Bonus",$id);
	$this->processWallet($sid,$mb,15,3,"Stage 2, $pa Matching Bonus",$id);
	}
	return $ret;
}


function shiftToStage4($id,$pack){
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$key = userName($id,'sn');
	$suser = userName($id,'sponsor');
	$sid = userName2($suser,'id');
	$stage = userName($id,$stg);
$ret=0;
//	$n = $this->totalPackStageTeam($key,$stage,$pack);
	$n = $this->packStageTeam($key,$stage,$pack);
	$team = '';//
	if($n==14 AND $stage==3){
	if($pack==50){$sb=35;$mb=20;$cb=35;}elseif($pack==25){$sb=28;$mb=16;$cb=28;}else{$sb=7;$mb=4;$cb=7;}
	$db->query("UPDATE user SET $stg=4 WHERE sn='$key' ");
	$ret = 1;
	$this->logUserStage($id,3,$team,$pack);
	$pa = $this->typeTitle($pack);
	$this->processWallet($id,$sb,13,4,"Stage 3, $pa Stepout Bonus",$id);
	$this->processWallet($id,$cb,17,4,"Stage 3, $pa Charity Bonus",$id);
	$this->processWallet($sid,$mb,15,4,"Stage 3, $pa Matching Bonus",$id);
	}
	return $ret;
}


function shiftToStage5($id,$pack){
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$key = userName($id,'sn');
	$suser = userName($id,'sponsor');
	$sid = userName2($suser,'id');
	$stage = userName($id,$stg);
$ret=0;
	//$n = $this->totalPackStageTeam($key,$stage,$pack);
	$n = $this->packStageTeam($key,$stage,$pack);
	$team = '';//
	if($n==14 AND $stage==4){
	if($pack==50){$sb=200;$mb=150;$cb=125;}elseif($pack==25){$sb=160;$mb=120;$cb=100;}else{$sb=40;$mb=30;$cb=25;}
	$db->query("UPDATE user SET $stg=5 WHERE sn='$key' ");
	$ret = 1;
	$this->logUserStage($id,3,$team,$pack);
	$pa = $this->typeTitle($pack);
	$this->processWallet($id,$sb,13,5,"Stage 4, $pa Stepout Bonus",$id);
	$this->processWallet($id,$cb,17,5,"Stage 4, $pa Stepout Bonus",$id);
	$this->processWallet($sid,$mb,15,5,"Stage 4, $pa Matching Bonus",$id);
	}
	return $ret;
}




function shiftAll($stage,$pack){
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$sql = $db->query("SELECT * FROM user WHERE $stg>='$stage'");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
	if($stage==1){$this->shiftToStage2($id,$pack);}
	elseif($stage==2){$this->shiftToStage3($id,$pack);}
	elseif($stage==3){$this->shiftToStage4($id,$pack);}
	elseif($stage==4){$this->shiftToStage5($id,$pack);}
	}
	return;
}


function promoteUserToStage3($id){
	global $db;
	$ret = 0;
	$key = userName($id,'sn');
	$pack = userName($id,'pack');
	$stage = userName($id,'stage');
	$teamvip = $this->stageTeam($key,1);
	$team = $this->teamHeads($key,$stage);
	$countteam = count($team);
	$team = json_encode($team);
	if($countteam==14 AND $pack==50 AND $stage==2){$ret = 1; //at every upgrade check for this ctiteria
		$db->query("UPDATE user SET stage=3 WHERE sn='$key' ");
		$this->logUserStage($id,3,$team,$teamvip);
			if($teamvip==14){ //pay stepout and matching
				$stepoutbonus = $this->stepoutBonus($id,3); 
				$matchingbonus = $this->matchingBonus(3);
				$sponsor = userName($id,'sponsor');
				$sponsorid = userName2($sponsor,'id');
				$this->processWallet($id,$stepoutbonus,13,3,'Stage 2 Stepout Bonus',$id);
				$this->processWallet($sponsorid,$matchingbonus,15,3,'Stage 2 Matching Bonus',$id);
			}
	}
return $ret;
}

function promoteUserToStage4($id){
	global $db;
	$ret = 0;
	$key = userName($id,'sn');
	$pack = userName($id,'pack');
	$stage = userName($id,'stage');
	$teamvip = $this->stageTeam($key);
	$team = $this->teamHeads($key,$stage);
//	$countteam = count($team);
	$team = json_encode($team);
	$vipcount = $this->totalStageTeamReq($key,50,128);//totalPackTeam($key,50);
	if($teamvip==14 AND $stage==3 AND $vipcount>255){$ret = 1; 
		$db->query("UPDATE user SET stage=4 WHERE sn='$key' ");
		$this->logUserStage($id,3,$team,$teamvip);
			 //pay stepout and matching
				$stepoutbonus = $this->stepoutBonus($id,4); 
				$matchingbonus = $this->matchingBonus(4);

				$incentivebonus = $this->incentiveBonus(4);
				$charitybonus = $this->charityBonus(4);
				$sponsor = userName($id,'sponsor');
				$sponsorid = userName2($sponsor,'id');
				$this->processWallet($id,$stepoutbonus,13,4,'Stage 3 Stepout Bonus',$id); //stepout
				$this->processWallet($sponsorid,$matchingbonus,15,4,'Stage 3 Matching Bonus',$id); //matching
				
				$this->processWallet($id,$incentivebonus,15,4,'Stage 3 Incentive Bonus',$id); //incentive
				$this->processWallet($id,$charitybonus,15,4,'Stage 3 Charity Bonus',$id); //charity
			
	}
return $ret;
}


function promoteUserToStage5($id){
	global $db;
	$ret = 0;
	$key = userName($id,'sn');
	$pack = userName($id,'pack');
	$stage = userName($id,'stage');
	$teamvip = $this->stageTeam($key);
	$team = $this->teamHeads($key,$stage);
//	$countteam = count($team);
	$team = json_encode($team);
	$vipcount = $this->totalStageTeamReq($key,50,1152);;//$this->totalPackTeam($key,50);
	if($teamvip==14 AND $stage==4 AND $vipcount>2303){$ret = 1; 
		$db->query("UPDATE user SET stage=5 WHERE sn='$key' ");
		$this->logUserStage($id,3,$team,$teamvip);
			 //pay stepout and matching
				$stepoutbonus = $this->stepoutBonus($id,5); 
				$matchingbonus = $this->matchingBonus(5);
				
				$incentivebonus = $this->incentiveBonus(5);
				$charitybonus = $this->charityBonus(5);

				$sponsor = userName($id,'sponsor');
				$sponsorid = userName2($sponsor,'id');
				$this->processWallet($id,$stepoutbonus,13,5,'Stage 4 Stepout Bonus',$id);
				$this->processWallet($sponsorid,$matchingbonus,15,5,'Stage 4 Matching Bonus',$id);
				
				$this->processWallet($id,$incentivebonus,15,5,'Stage 4 Incentive Bonus',$id); //incentive
				$this->processWallet($id,$charitybonus,15,5,'Stage 4 Charity Bonus',$id); //charity		
	}
return $ret;
}



function payMatrixBonus($id,$stage,$pack)
{
	$key = userName($id,'sn');
	$team = $this->stageTeamHeads($key,$stage,$pack);

	$i=0;
	while($i<count($team)){$e=$i++;
		$head = $team[$e];
		$headid = userNameSn($head,'id');
		$matrixbonus = $this->matrixBonus($pack,$stage);
		if(sqL5('wallet','id',$id,'type',12,'stage',$stage,'opt',$headid,'cos',$matrixbonus)==0){
			$pa = $this->typeTitle($pack);
$this->processWallet($id,$matrixbonus,12,$stage,"Stage $stage, $pa Matrix Bonus",$headid);	
	}	
	}
return; 
}


//pay referal upgrade bonus separately before paying this
function payUpgradeBonuses($id,$amount){
//stepout bonus upgrade for stage 2 users who are a1 or a2
$this->stage1StepoutUpgrade($id,$amount);
//pay matrix bonus upgrade to all that have previously received matrix bonus from the user
//loop 50
$key = userName($id,'sn');
$remedybonus = round(5*$amount/50,2);
$i=1;
while($i<50){$e=$i++;
$key = userNameSn($key,'a1');

$idx = userNameSn($key,'id');
if(sqL4('wallet','id',$idx,'opt',$id,'type',12,'stage',2)>0){
$this->processWallet($idx,$remedybonus,12,'2','Stage 2 Matrix Bonus Upgrade',$id);
	}
	//check for and pay missed stepout and matching bonuses
	$teamvip = $this->stageTeam($key,1);//
if($teamvip==14 AND sqL3('wallet','id',$idx,'type',13,'stage',3)==0){ //pay stepout and matching
				$stepoutbonus = $this->stepoutBonus($idx,3); 
				$matchingbonus = $this->matchingBonus(3);
				$sponsor = userName($idx,'sponsor');
				$sponsorid = userName2($sponsor,'id');
				$this->processWallet($idx,$stepoutbonus,13,3,'Stage 2 Stepout Bonus',$id);
				$this->processWallet($sponsorid,$matchingbonus,15,3,'Stage 2 Matching Bonus',$id);
			}


}

return; 
}



function promoteUserToStage2All(){
	global $db;
	$sql = $db->query("SELECT * FROM user WHERE stage=1");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
		$this->promoteUserToStage2($id);
	}
	return;
}


function promoteUserToStage3All(){
	global $db;
	$sql = $db->query("SELECT * FROM user WHERE stage=2");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
		$this->promoteUserToStage3($id);
	}
	return;
}


function promoteUserToStage4All(){
	global $db; $a=0;
	$sql = $db->query("SELECT * FROM user WHERE stage=3");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
	$x = $this->promoteUserToStage4($id);
	$a += $x;
	}
	if($a>0){$this->promoteUserToStage5All(); }
	return;
}


function promoteUserToStage5All(){
	global $db;
	$sql = $db->query("SELECT * FROM user WHERE stage=4");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
		$this->promoteUserToStage5($id);
	}
	return;
}

function payMatrixBonusAllStage($stage,$pack){ //start from stage 2
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;

	$sql = $db->query("SELECT * FROM user WHERE $stg>='$stage' ");
	while($row=mysqli_fetch_assoc($sql)){
		$id = $row['id'];
		$this->payMatrixBonus($id,$stage,$pack);
	}
	return;
}



function extractVipFromTeam($team){
global $db;
$i=0; $vip=0;
while($i<count($team)){ $e=$i++;
	$key = $team[$e];
	$pack = userNameSn($key,'pack');
	if($pack==50){$vip++; }
}
return $vip;	
}



//Maintenance Operations//


function upgradePlan($new){
	global $db,$report,$count;
 //= $_POST['upgrade'];
$id=$this->Uid();
$type = userName($id,'pack');
$stage = userName($id,'stage');
$key = userName($id,'sn');


$amount = $new - $type;
$bal = $this->wallet($id);
if($bal<$amount){$report= 'Insufficient Balance'; $count=1; return;}
$this->processWallet($id,$amount,5,'','Account Upgrade',$id);
$this->logActivationAndUpgrade($id,$amount,2);//log activation

//pay stepout bonus Upgrade
$db->query("UPDATE user SET pack='$new' WHERE id='$id' ");
if($new==25){$db->query("UPDATE user SET stage25=1 WHERE id='$id' "); }
elseif($new==50 AND $type==5){$db->query("UPDATE user SET stage25=1, stage50=1 WHERE id='$id' "); }
elseif($new==50 AND $type==25){$db->query("UPDATE user SET stage50=1 WHERE id='$id' "); }

//Pay ref bonus
$bonus = $amount/5; 
$sponsor = sqLx('user','id',$id,'sponsor');
$sponsorid = sqLx('user','user',$sponsor,'id');
$this->processWallet($sponsorid,$bonus,11,'','Referral Bonus Upgrade',$id);
$this->shareRevenue($amount,$id);
//Upgrade User Account

//$this->payUpgradeBonuses($id,$amount);

 //promote all

  $pro->shiftAll(1,25); 
  $pro->shiftAll(2,25); 
  if($new>25){
  $pro->shiftAll(1,50); 
  $pro->shiftAll(2,50);
}
   //pay matrix bonus to all
 $pro->payMatrixBonusAllStage(2,25); 
 $pro->payMatrixBonusAllStage(3,25); 
   if($new>25){
 $pro->payMatrixBonusAllStage(2,50); 
 $pro->payMatrixBonusAllStage(3,50); 
}
$report= 'User Account Successfully Updated';
return;
}

function upgradePlanAmend(){
	global $db,$report,$count;
	$user = $_GET['user'];
$idx = userName2($user,'id');
$amount = 45;
$id = $_SESSION['Fid'];
$remedybonus = round(5*$amount/50,2);
$this->processWallet($idx,$remedybonus,12,'2','Stage 2 Matrix Bonus Upgrade',$id);

return;
}




function promoteUplines($id,$pack){
	global $db;
	$key = userName($id,'a2');

	$upcount = sqL1('user','a2',$key);
	if($upcount==4){ //
	$keyid = $this->keyToId($key);
	$this->shiftToStage2($keyid,5);
	if($pack>5){$this->shiftToStage2($keyid,25);}
	if($pack>25){$this->shiftToStage2($keyid,50);}

	$i=1; $a = 0; 
	while($i<49){ $e = $i++; 
	$key = userNameSn($key,'a1');
	if($key==0){return; }
	$idx = userNameSn($key,'id');
					$this->payMatrixBonus($idx,2,5);
	if($pack>5){$this->payMatrixBonus($idx,2,25);}
	if($pack>25){$this->payMatrixBonus($idx,2,50);}

$a += $this->shiftToStage3($idx,5);//check for further promotion
if($pack>5){$a += $this->shiftToStage3($idx,25);}
	if($pack>25){$a += $this->shiftToStage3($idx,50);}

	}
if($a>0){
						$this->payMatrixBonusAllStage(3,5);;
	if($pack>5){$this->payMatrixBonusAllStage(3,25);}
	if($pack>25){$this->payMatrixBonusAllStage(3,50);}

	         $this->$pro->shiftAll(3,5);
if($pack>5){$this->shiftAll(3,25);}
if($pack>25){$this->shiftAll(3,50);}
}
	}
return; 
}





function matrixBonus($pack,$stage){
	$p=0.1;
if($pack==50){$p=0.5;}elseif($pack==25){$p=0.4;}elseif($pack==5){$p=0.1;}
	$mb=0;
if($stage==2){$mb = 5; }
elseif($stage==3){$mb = 20; }
elseif($stage==4){$mb = 100; }
elseif($stage==5){$mb = 400; }
elseif($stage==6){$mb = 1000; }

return round($mb*$p,2);
}


function matchingBonus($stage){
	$mb=0;
if($stage==2){$mb = 2; }
elseif($stage==3){$mb = 8; }
elseif($stage==4){$mb = 40; }
elseif($stage==5){$mb = 300; }
elseif($stage==6){$mb = 1500; }
elseif($stage==7){$mb = 5000; }
return $mb;
}




function charityBonus($stage){
	$mb=0;
if($stage==2){$mb = 0; }
elseif($stage==3){$mb = 0; }
elseif($stage==4){$mb = 70; }
elseif($stage==5){$mb = 250; }
elseif($stage==6){$mb = 1500; }
elseif($stage==7){$mb = 5000; }
return $mb;
}




function incentiveBonus($stage){
	$mb=0;
if($stage==2){$mb = 0; }
elseif($stage==3){$mb = 0; }
elseif($stage==4){$mb = 1000; }
elseif($stage==5){$mb = 11300; }
elseif($stage==6){$mb = 25500; }
elseif($stage==7){$mb = 121000; }
return $mb;
}


function stage1Stepout($id){
	global $db;
	$x = userName($id,'sn');
	$sum=0;
	$sql = $db->query("SELECT * FROM user WHERE a1='$x' OR a2='$x' ");
while($row=mysqli_fetch_assoc($sql)){
	$sum += $row['pack']/25;
}
return $sum;
}

function stage1StepoutUpgrade($id,$amount){
	$a1 = userName($id,'a1');
	$a2 = userName($id,'a2');
	if(sqLx('user','sn',$a1,'stage')>1){
		$bonus = round($amount/25,2);
		$id1 = sqLx('user','sn',$a1,'id');
		$this->processWallet($id1,$bonus,13,'2','Stage 1 Stepout Bonus Upgrade',$id);
	}
	if(sqLx('user','sn',$a2,'stage')>1){
		$bonus = round($amount/25,2);
		$id2 = sqLx('user','sn',$a2,'id');
		$this->processWallet($id2,$bonus,13,'2','Stage 1 Stepout Bonus Upgrade',$id);
	}
	return;
}

function stepoutBonus($id,$stage){
	
	//$type = userName($id,'pack');
if($stage==1){return round($this->stage1Stepout($id),2); }
	$mb=0;
if($stage==2){$mb = 12; }
elseif($stage==3){$mb = 16; }
elseif($stage==4){$mb = 70; }
elseif($stage==5){$mb = 400; }
elseif($stage==6){$mb = 5000; }
elseif($stage==7){$mb = 15000; }
//return round($mb*$type/50,2);
return $mb;
}

function PayUnpaid()
{ global $report;
	$key = $_POST['PayUnpaid'];
	$stage = userNameSn($key,'stage');
	$report = $this->unpaidMatrixStepoutBonus($key,$stage);
	//$report = 'Operation Successful '.$stage.$key;
}


function unpaidMatrixStepoutBonus($key,$newstage)
{
	//$team = $this->stageTeam($key);
	$team = $this->stageTeamHeads($key,$newstage);
	$id = userNameSn($key,'id');
	$stepoutbonus = $this->stepoutBonus($id,$newstage);

	$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$matchingbonus = $this->matchingBonus($newstage);


	$i=0;
	while($i<count($team)){$e=$i++;
		$head = $team[$e];
		$headid = userNameSn($head,'id');
		$matrixbonus = $this->matrixBonus($headid,$newstage);
		if(sqL4('wallet','id',$id,'type',12,'stage',$newstage,'opt',$headid)==0){
		$this->processWallet($id,$matrixbonus,12,$newstage,'Stage '.$newstage.' Matrix Bonus',$headid);
			//echo $matrixbonus.', ';
	}
		
	}
//pay stepout bonus
		if(sqL3('wallet','id',$id,'type',13,'stage',$newstage)==0){
$this->processWallet($id,$stepoutbonus,13,$newstage,'Stage '.$newstage.' Stepout Bonus',$id);
	}
//pay matching bonus
if(sqL4('wallet','id',$upid,'type',15,'stage',$newstage,'opt',$id)==0){
$this->processWallet($upid,$matchingbonus,15,$newstage,'Stage '.$newstage.' Matching Bonus',$id);
}

return;// json_encode($team) .sqL3('wallet','id',$id,'type',12,'stage',$newstage); 
}



function stageUnpaidBonuses($stage=3)
{
global $db;
$sql = $db->query("SELECT * FROM user WHERE stage = '$stage' ");
while($row=mysqli_fetch_assoc($sql)){
	$key = $row['sn'];
	$this->unpaidMatrixStepoutBonus($key,$stage);
}
return;
}


function ForcePromote()
{global $report;
	$key = $_POST['ForcePromote'];
	$this->promoteUplines2($key);
	$report='Opereation Successful';
}

function promoteUplines2($key)
{
	global $db;
	$key2=$key;
	$stage = userNameSn($key,'stage');
	$type = userNameSn($key,'pack');
	$team = $this->stageTeamx($key);
	if($team == 14 AND $type == 50){
		$newstage = $stage+1;
$db->query("UPDATE user SET stage='$newstage',team=0 WHERE sn='$key' "); //upgrade to new stage
//$this->unpaidMatrixBonus($key,$newstage){} //check for unpaid matrix bonuses
$id = userNameSn($key,'id');
$vipteam = $this->stageTeam($key);
if($vipteam>=14){
//pay stepout bonus
$stepoutbonus = $this->stepoutBonus($id,$newstage);
$this->processWallet($id,$stepoutbonus,13,$newstage,'Stage '.$newstage.' Stepout Bonus',$id);

//pay matching bonus
 $upuser = sqLx('user','sn',$key,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$matchingbonus = $this->matchingBonus($newstage);
$this->processWallet($upid,$matchingbonus,15,$newstage,'Stage '.$newstage.' Matching Bonus',$id);
}

//pay mat bonus to 50 gen
//etre
$bonus = $this->stageMatBonus($newstage);
		$i=1;
	while($i<48){ $e = $i++; 
	$key = userNameSn($key,'a1');
	if($key==0){return; }
if(userNameSn($key,'stage')==$newstage){ 
	$team = $this->stageTeamx($key);
if($team>userNameSn($key,'team')){  	
	$idx = userNameSn($key,'id');
$this->processWallet($idx,$bonus,12,$newstage,'Stage '.$newstage.' Matrix Bonus',$id);/*pay matrix*/
$db->query("UPDATE user SET team='$team' WHERE sn='$key' ");//update team
}
}
	}

	}
return; 	
}

function stageMatBonus($stage){
	if($stage==2){$bonus=5; }
elseif($stage==3){$bonus=20; }
elseif($stage==4){$bonus=100; }
elseif($stage==5){$bonus=400; }
elseif($stage==6){$bonus=1000; }
return $bonus; 
}

function uplineId($id){

		$user =  sqLx('user','id',$id,'sponsor');
		$sponsorid = sqLx('user','user',$user,'id');
		return $sponsorid;
	}


function updateUplines($id){
	global $db;
	$upli = sqLx('user','id',$id,'upline');
	$uplikey = sqLx('user','user',$upli,'sn');
	$upline = $this->findUpline($uplikey);
	
	$sql = $db->query("SELECT * FROM user WHERE sn='$upline' ");
	$row = mysqli_fetch_assoc($sql);
	$a1 = $row['sn']; 
	$a2 = $row['a1']; 
	$a3 = $row['a2']; 
	$a4 = $row['a3']; 
	$a5 = $row['a4']; 
	$a6 = $row['a5']; 
	$a7 = $row['a6']; 
	$a8 = $row['a7']; 
	$a9 = $row['a8']; 
	$a10 = $row['a9']; 

	$a11 = $row['a10']; 
	$a12 = $row['a11']; 
	$a13 = $row['a12']; 
	$a14 = $row['a13']; 
	$a15 = $row['a14']; 
	$a16 = $row['a15']; 
	$a17 = $row['a16']; 
	$a18 = $row['a17']; 
	$a19 = $row['a18']; 
	$a20 = $row['a19']; 

	$a21 = $row['a20']; 
	$a22 = $row['a21']; 
	$a23 = $row['a22']; 
	$a24 = $row['a23']; 
	$a25 = $row['a24']; 
	$a26 = $row['a25']; 
	$a27 = $row['a26']; 
	$a28 = $row['a27']; 
	$a29 = $row['a28']; 
	$a30 = $row['a29']; 

	$a31 = $row['a30']; 
	$a32 = $row['a31']; 
	$a33 = $row['a32']; 
	$a34 = $row['a33']; 
	$a35 = $row['a34']; 
	$a36 = $row['a35']; 
	$a37 = $row['a36']; 
	$a38 = $row['a37']; 
	$a39 = $row['a38']; 
	$a40 = $row['a39']; 

	$a41 = $row['a40']; 
	$a42 = $row['a41']; 
	$a43 = $row['a42']; 
	$a44 = $row['a43']; 
	$a45 = $row['a44']; 
	$a46 = $row['a45']; 
	$a47 = $row['a46']; 
	$a48 = $row['a47']; 
	$a49 = $row['a48']; 
	$a50 = $row['a49']; 
	$g = $row['g']+1; 

	$db->query("UPDATE user SET a1='$a1', a2='$a2', a3='$a3', a4='$a4', a5='$a5', a6='$a6', a7='$a7', a8='$a8', a9='$a9', a10='$a10', a11='$a11', a12='$a12', a13='$a13', a14='$a14', a15='$a15', a16='$a16', a17='$a17', a18='$a18', a19='$a19', a20='$a20', a21='$a21', a22='$a22', a23='$a23', a24='$a24', a25='$a25', a26='$a26', a27='$a27', a28='$a28', a29='$a29', a30='$a30', a31='$a31', a32='$a32', a33='$a33', a34='$a34', a35='$a35', a36='$a36', a37='$a37', a38='$a38', a39='$a39', a40='$a40', a41='$a41', a42='$a42', a43='$a43', a44='$a44', a45='$a45', a46='$a46', a47='$a47', a48='$a48', a49='$a49', a50='$a50', g='$g' WHERE id='$id' ");

$active = sqL1('user','a1',$upline);
$db->query("UPDATE user SET active='$active' WHERE sn='$upline' ");
return;
}





function findUpline($sponsorkey){
	global $db;

	if(sqLx('user','sn',$sponsorkey,'active')<2){return $sponsorkey; }
	$i =1; 
	while($i<=50){ $e = $i++;
		$a = 'a'.$e;
	$sql = $db->query("SELECT * FROM user WHERE $a='$sponsorkey' ORDER BY a1 ASC, a2 ASC, a3 ASC ");
	while($row = mysqli_fetch_assoc($sql)){
	if($row['active']<2){return $row['sn']; }
	}
  }
}

	function ApproveFundOrder()
	{
		global $db,$report, $count;
		
		$sn = $_POST['ref'];
		$id = sqLx('walletorder','sn',$sn,'id');
		$type = sqLx('walletorder','sn',$sn,'type');
		$amt =sqLx('walletorder','sn',$sn,'amount');
		if($type=='USD'){
$amt = round(sqLx('walletorder','sn',$sn,'amount')/sqLx('setup','sn',1,'ntod_d'),2);
		}
		
$uid = $this->Uid();
		$amount = $_POST['amount'];
		$amount = str_replace(',','',$amount);
		$pass = $_POST['pass'];
		$password = userName($uid,'pass');
if($amt != $amount){ $report = 'Wrong amount '.$amount.$amt; $count = 1; return; }

	$paymentdate = time();

		
	
		if(password_verify($pass, $password)){
			if(sqL2('walletnaira','type',19,'opt',$sn)){return;}
			if($type=='USD'){
				if(sqL2('wallet','type',19,'opt',$sn)>0){return;}
			$this->processWallet($id,$amt,19,'','Wallet Funding by Admin',$sn);
			}else{
				if(sqL2('walletnaira','type',19,'opt',$sn)>0){return;}
$this->processWalletNaira($id,$amt,19,'','Wallet Funding by Admin',$sn);	
			}
			$db->query("UPDATE walletorder SET approvedate='$paymentdate', amount2='$amount', status=9 WHERE sn='$sn' ");
			$report = "Wallet Funding successful";
				$message = 'Congratulations '.userName($id).'<br><br>


Your payment request have been Successfully Approved <br><br>

Kindly proceed with desired Transaction.<br><br>

Thank You!<br><br>


#FinationGlobalTeam';
$email = userName($id,'email');
$this->emailer($email,$message,'Fination Global Funding Approval');


		}else{
			$report = "Authentication failed. try again";
			$count = 1;
		}
		return;
	}


	function ApproveWithdrawal()
	{
		global $db,$report, $count;

		$ref = $_POST['ApproveWithdrawal'];
		$st = sqLx('wallet','opt',$ref,'status')+1;
		if($st<3){
			$db->query("UPDATE wallet SET status='$st' WHERE opt='$ref' ");
			$report = $st==1 ? 'Operation successful, Click pay again to complete' : 'Operation successful';
		}
		return;
	}
	function ReserseWithdrawal()
	{
		global $db,$report, $count;
		$ref = $_POST['ReserseWithdrawal'];

		$db->query("DELETE FROM wallet WHERE opt='$ref' ");
		$report = 'Operation successful';

		return;
	}
	
	function DeductFund()
	{
		global $db,$report, $count;

		$userKey = $_POST['DeductFund'];
		
		$pass = $_POST['password'];
		$paymentdate = time();
		$password = $this->userName4('pass');
		$remark = 'Debit by Admin';
		$type = 1;
		$status = 9;

		$amount = $_POST['amount'];
		
		#should be able to send the money directly to the users account..
		
		if(password_verify($pass, $password)){

			$this->processWallet($userKey,$amount,$type,'',$remark);
			$report = 'successfully deducted NGN'.number_format($amount).' from '.userName($userKey);
		}
		
		else {
			$report = "Authentication failed. try again";
			$count = 1;
		}
		return;
	}
	// dispalys the wallet status messages...
	function walletStatus($status)
	{
		
		if($status==0){$r='<font color="red">Pending</font>'; }
		elseif($status==1){$r='<font color="#036">Processing...</font>'; }
		elseif($status==2){$r='<font color="green">Success</font>'; }
		
		else{$r='<font color="red">Error</font>';}
		return $r;
	}

	function Deactivate(){
		global $db, $report; 
		$fid = $_POST['fid'];
		$status = $_POST['Deactivate'];

		$db->query("UPDATE user SET status='$status' WHERE id='$fid'"); 
		$report = 'Operation successful';
		return;
	}
	function ActivatePro(){
		global $db, $report; 
		$ref = $_GET['ref'];
		$status = $_POST['ActivatePro'];
		$db->query("UPDATE ginvest SET status='$status' WHERE ref='$ref'"); 
		$report = 'Operation successful';
		return;
	}



	function ActivateSell(){
		global $db, $report; 
		$ref = $_GET['ref'];
		$status = $_POST['ActivateSell'];
		$db->query("UPDATE ginvest SET sell='$status' WHERE ref='$ref'"); 
		$report = 'Operation successful';
		return;
	}




	function idToPackNo($id)
	{
		global $db;
        	$userpack = $this->sqLz('user','id', $id,'package'); // error log...
        	if(empty($userpack)){
        		return 0;
        	}else{
        		return $this->sqLz('package','keyy', $userpack,'packno'); 
        	}
        }
        function processpoint($spid2, $points, $user1)
        {
        	global $db, $report;
        	$ctime = time();
        	$points=abs($points);
        	$sql = $db->query("INSERT INTO pvalue (id, points, reference, ctime) VALUES('$spid2', '$points', 
        		'$user1', '$ctime')");
        	return ;
        }
        function CreateSavings()
        {
        	global $db, $report;
        	extract($_POST);
        	$ctime = time();
        	$id = $this->Uid();
        	$ref = $this->win_hash(10);
        	$start = time();
        	
        	$sql = $db->query("INSERT INTO savings (id, title, amount, duration, freq,ref,start,type) VALUES('$id', '$title', 
        		'$amount', '$duration','$freq','$ref','$start','$type')");
        	$report = 'Automated Savings Successfully Created';
        	return ;
        }

        function CreateGroupInvest()
        {
        	global $db, $report;
        	extract($_POST);
        	$ctime = time();
        	$id = $this->Uid();
        	$ref = $this->win_hash(10);
        	//$start = time();
        	
        	$sql = $db->query("INSERT INTO ginvest (title, note, amount, slot, ref,type) VALUES('$title', 
        		'$note', '$amount','$slot','$ref','$type')");
        	$report = 'Group Investment Successfully Created';
        	return ;
        }


        function UpdateGroupInvest()
        {
        	global $db, $report;
        	extract($_POST);
        	$ctime = time();
        	$id = $this->Uid();
        	$ref = $_GET['ref'];
        	//$start = time();
        	
        	$sql = $db->query("UPDATE ginvest SET title='$title', note='$note', amount='$amount', slot='$slot', com='$com', com2='$com2' WHERE ref='$ref' ");
        	$report = 'Investment Plan Successfully Updated';
        	return ;
        }

        function savingsDeduction($ref,$circles){
        	global $db;
$id = sqLx('savings','ref',$ref,'id');
$status = sqLx('savings','ref',$ref,'status');
$bal = $this->wallet($id);
$deducted = $this->DeductedSav($ref);
$amount = $this->SavFreq($ref,2);
$due = $amount*$circles-$deducted;
if($bal>=$amount){ 
        	$this->processWallet($id,$amount,6,'','Automated Savings',$ref);
if($status==0){$db->query("UPDATE savings SET status=2 WHERE ref='$ref' "); }
        }
        //pay pending due
// $bal = $this->wallet($id);        
// if($due>$amount AND $bal>=$amount){ 
//         	$this->processWallet($id,$amount,6,'','Aur=tomated Savings',$ref);
// if($status==0){$db->query("UPDATE savings SET status=2 WHERE ref='$ref' "); }
//         }
        return;
    }

 function DeductAutomated(){
 	global $db;
 	$sql = $db->query("SELECT * FROM savings");
 	while($row=mysqli_fetch_assoc($sql)){
 		$x = ceil((time() - $row['start'])/86400);
 		$f = $row['freq'];
 		if($f==1){$g=1;}
 		elseif($f==2){$g=7;}
 		elseif($f==3){$g=30;}
 		$rem = $x%$g;
 		$circles = floor($x/$g);
 		if($rem==0){$this->savingsDeduction($row['ref'],$circles); }
 	}
 	return;
 }
 

 function InvestFunds()
        {
        	global $db, $report,$count;
        	extract($_POST);
        	$ctime = time();
        	$id = $this->Uid();
        	$balance = $this->wallet($id);
        	$balance2 = $this->walletnaira($id);
        	if($balance < $amount AND $type=='USD'){
			$report= "You have insufficient balance.";
			$count=1; 
			return;
		}
        	if($balance2 < $amount AND $type=='NGN'){
			$report= "You have insufficient balance.";
			$count=1; 
			return;
		}	
			$roi  = $amount*1.3;
        	$start = time();
        	$end = $start + 86400*365;
        	$ref = $this->win_hash(10);
        	if($type=='USD'){
        	$this->processWallet($id,$amount,7,'','Fund Investment',$ref);
        }else{
        	$this->processWalletNaira($id,$amount,7,'','Fund Investment',$ref);
        }
        	$sql = $db->query("INSERT INTO invest (id, title, amount, roi, start,end,ref,type) VALUES('$id', '$title', 
        		'$amount','$roi', '$start', '$end', '$ref', '$type')");

$upuser = userName($id,'sponsor');
	$upid = sqLx('user','user',$upuser,'id');//userName($upuser,'id');
	$upack = userName($upid,'pack');

	if($upack==50){$com = 5;}elseif($upack==25){$com = 4;}else{$com = 3;}
	$bonus = $amount*$com*0.01;
   $this->processWallet($upid,$bonus,16,1,'Investment Commission',$id);

        	$report = 'Automated Savings Successfully Created';
        	return ;
        }

        function SavFreq($ref,$opt=''){
$amt = sqLx('savings','ref',$ref,'amount');
$duration = sqLx('savings','ref',$ref,'duration');
$freq = sqLx('savings','ref',$ref,'freq');

if($freq==1){$x = $duration*30; $v = ' Daily';}
elseif($freq==2){$x = $duration*4; $v = ' Weekly';}
elseif($freq==3){$x = $duration*1; $v = ' Monthly';}
$p = $amt/$x;
return $opt=='' ? number_format($p,2).$v : $p;
        }

        function payClient(){
        	global $db, $report, $count;
        	$id = $_POST['clientid'];
        	$payval = $_POST['payClient'];
        	$ctime = time();
		//update the payorder table 
        	$payout = $db->query("UPDATE payoutorder SET paidstatus='$payval', ctime='$ctime' WHERE id='$id'");
		//$db->query("UPDATE pvalue SET points=0 WHERE id='$id'");
        	$report = 'Client Paid Successfully';

        }
        function requestPayout(){
        	global $db, $report, $count;
        	$uid = $this->Uid(); $ps=0;
        	$totalpv = $this->pvpicker($uid, 'points');
        	if($totalpv>=500){
        		if($totalpv>=71000){$rem = 'NGN3,000,000 Car Fund'; $pv=50000;}
        		elseif($totalpv>=21000){$rem = 'NGN500,000 Expense Paid Trip'; $pv=10000;}
        		elseif($totalpv>=11000){$rem = 'NGN200,000 Educational Support Fund'; $pv=6000;}
        		elseif($totalpv>=5000){$rem = 'NGN100,000 Laptop Fund'; $pv=3000;}
        		elseif($totalpv>=2000){$rem = 'NGN50,000 Phone Bonus'; $pv=1500; }
        		elseif($totalpv>=500){$rem = 'NGN20,000 Cash Incentive'; $pv=500; }
        		
        		$ps = $this->payBonus($rem,$pv);
        	}
        	if($ps==1){$report = 'You have successfully placed order for '.$rem;}
        	else{$report = 'You are currently not yet qualified for an incentive ';}
        	return;
        }

        function payBonus($rem,$pv){
        	global $db, $report, $count;
        	$res = 0;
        	$uid = $this->Uid();
        	$sql = $db->query("SELECT * FROM payoutorder WHERE id ='$uid' AND totalpt = '$pv' ");
        	if(mysqli_num_rows($sql)==0){
        		$db->query("INSERT INTO payoutorder (id,totalpt,remark) VALUES ('$uid','$pv','$rem') "); $res=1;
        	}
        	return $res;
        }
        function idToAccDetails($id, $col){
        	global $db, $report, $count;
        	$sql = $db->query("SELECT * FROM user WHERE id='$id'");
        	$accdetails = $sql->fetch_assoc();
        	return $accdetails[$col];

        }
        function idToName($id, $col='firstname'){
        	global $db; 
        	$sql = $db->query("SELECT * FROM user WHERE id ='$id'");
        	$res = $sql->fetch_assoc();
        	$result = ($col == 'firstname') ? $res['firstname'].' '.$res['lastname'] : $res[$col];
        	return $result;
        }

        function keyToId($sn, $col = 'id')
        {
        	global $db;
        	$que = $db->query("SELECT * FROM user WHERE sn = '$sn' ") or die(mysqli_error());
        	$ro = mysqli_fetch_array($que);
        	return $ro[$col];
        }
        function payoutsum(){
        	global $db; 
        	$id = $this->Uid();
        	$sql= $db->query("SELECT SUM(points) AS pointsum FROM pvalue WHERE id='$id'");
        	$row = $sql->fetch_assoc();
		//print_r(json_encode($row)); exit;
        	$pointsum  = ($row['pointsum']) ? $row['pointsum'] : 0 ;
        	$name = $this->idToName($id);
        	$db->query("UPDATE payoutorder SET name = '$name', totalpt='$pointsum' WHERE id='$id'") or die(mysqli_error());
        }
	//USED ONCE FOR AUTO UPDATE..
// 	function updatePay(){
// 		global $db; 
// 		$sql = $db->query("SELECT * FROM user");
// 		while($row = $sql->fetch_assoc()){
// 			$id = $row['id'];
// 			$db->query("INSERT INTO payoutorder (id) VALUES('$id')");
// 		}

// 	}
        function pvpicker($id, $col){
        	global $db; 
        	$sql = $db->query("SELECT SUM(points) AS points_sum FROM pvalue WHERE id = '$id'");
        	$row = $sql->fetch_assoc();
        	$point = $row['points_sum'];
        	$val = ($col=='')? "": $point;

        	return abs($val);
        }
        function sqLx($table,$col1,$val1,$col)
        {
        	global $db;
        	$sql=$db->query("SELECT * FROM $table WHERE $col1='$val1' " )or die(mysqli_error());	
        	$row = mysqli_fetch_assoc($sql); 
        	return $row[$col];
        }
        function sqLz($table,$col1,$val1,$col='')
        {
        	global $db;
        	$sql=$db->query("SELECT * FROM $table WHERE $col1='$val1' " )or die(mysqli_error());	
        	$row = mysqli_fetch_assoc($sql); 
        	$val = ($col=='')? "": $row[$col];
        	return $val;
        }
        function adminLevel(){
        	$id = $this->Uid();

        	if(userName($id,'sn') == 1){return TRUE; }
        	else{return FALSE; }
        }

        function adminAccess(){
        	if($this->adminLevel()==FALSE){header('location: login.php'); exit;}
        }
        function usersLevel(){
        	$useraccess = $this->userName4('sn');
        	if($useraccess != 1){return TRUE; }
        	else{return FALSE; }
        }
        
        function userName($id,$col=''){
        	global $db;

        	$sql = $db->query("SELECT * FROM user WHERE id='$id'");
        	$row = $sql->fetch_assoc();
        	$val = ($col=='')?$row['firstname'].' '.$row['lastname']:$row[$col];
        	return $val;
        }
        function userName4($col = '')
        {
        	global $db, $userkey;

        	$que = $db->query("select * FROM user WHERE id = '$userkey' ") or die(mysqli_error());
        	$ro = mysqli_fetch_array($que);
        	if (!empty($col)) {
        		return $ro[$col];
        	} else {
        		return htmlspecialchars($ro['firstname'] . ' ' . $ro['lastname']);
        	}
        }

function stageTitle($stage){
        	$res='Inactive';
    if($stage==1){$res='Starter';}
elseif($stage==2){$res='Executive';}
elseif($stage==3){$res='Gold';}
elseif($stage==4){$res='Platinium';}
elseif($stage==5){$res='Diamond';}
elseif($stage==6){$res='Royal Diamond';}
return $res;
        }

function typeTitle($type){
        	$res='Inactive';
    if($type==5){$res='Regular';}
elseif($type==25){$res='Pro';}
elseif($type==50){$res='VIP';}
return $res;
        }


        function stageLevel($level){
        	$res=0;
        	if($level==1){$res=1;}
        	elseif($level==2){$res=0;}
        	elseif($level==3){$res=1;}
        	elseif($level==4){$res=0;}
        	elseif($level==5){$res=1;}
        	elseif($level==6){$res=0;}
        	elseif($level==7){$res=1;}
        	elseif($level==8){$res=0;}
        	elseif($level==9){$res=1;}
        	elseif($level==10){$res=2;}
        	elseif($level==11){$res=0;}
        	return $res;
        }
        function dataPercent($col=''){
        	global $db;
        	$sql = $db->query("SELECT * FROM compensation ");
        	$result = $sql->fetch_assoc();
        	$value = (!empty($result[$col]));
        	$no = $result['No'];
        	$val = ($no >= 1)? $value ."%" : $value;
        	return $val;
        // if($no >=1 ){ return $value . "%" ; }
        // else{return $value; }
        }
        function userName5($userKey,$col='')
        {
        	global $db;
	   # insert the user_id when invoking the function...
        	$que = $db->query("SELECT * FROM user WHERE id = '$userKey' ") or die(mysqli_error());
        	$ro = mysqli_fetch_array($que);
        	if (!empty($col)) {
        		return $ro[$col];
        	} else {
        		return htmlspecialchars($ro['firstname'] . ' ' . $ro['lastname']);
        	}
        }


        function processWallet($id,$amt,$type,$level,$remark,$opt='')
        {
global $db;
$agent = $_COOKIE['agent']??'';
if(sqL1('user','sn',$id)==1){$id = userName2($id,'id'); }

        	$ctime = time();
        	$sin = $this->wallet($id);
		$amt = ($type>10) ? $amt : '-'.$amt; //as cos
		$tan = $sin+$amt;
		$trno = $this->win_hash(12);

	//	if(sqL3('wallet','stage',$level,'cos',$amt,'id',$id)>0 AND $opt=='bonuses'){return; }
if($amt==0){return; }

		$status = 2; 
		$identity = $this->Uid();

$sql = $db->query("INSERT INTO wallet (id,trno,sin,cos,tan,type,status,stage,remark,ctime,rep,opt,agent) VALUES ('$id','$trno','$sin','$amt','$tan','$type','$status','$level','$remark','$ctime','$identity','$opt','$agent') ") or die(mysqli_error($db));
 
		return;
	} 


	function processWalletNaira($id,$amt,$type,$level,$remark,$opt='')
	{
global $db;
$agent = $_COOKIE['agent']??'';
if(sqL1('user','sn',$id)==1){$id = userName2($id,'id'); }

		$ctime = time();
		$sin = $this->wallet($id);
	$amt = ($type>10) ? $amt : '-'.$amt; //as cos
	$tan = $sin+$amt;
	$trno = $this->win_hash(12);

//	if(sqL3('wallet','stage',$level,'cos',$amt,'id',$id)>0 AND $opt=='bonuses'){return; }
if($amt==0){return; }

	$status = 2; 
	$identity = $this->Uid();

$sql = $db->query("INSERT INTO walletnaira (id,trno,sin,cos,tan,type,status,stage,remark,ctime,rep,opt,agent) VALUES ('$id','$trno','$sin','$amt','$tan','$type','$status','$level','$remark','$ctime','$identity','$opt','$agent') ") or die(mysqli_error($db));

	return;
} 

	   function processWalletPoint($id,$amt,$type,$level,$remark,$opt='')
        {
global $db;
$agent = $_COOKIE['agent']??'';
if(sqL1('user','sn',$id)==1){$id = userName2($id,'id'); }

        	$ctime = time();
        	$sin = $this->wallet($id);
		$amt = ($type>10) ? $amt : '-'.$amt; //as cos
		$tan = $sin+$amt;
		$trno = $this->win_hash(12);

		$status = 2; 
		$identity = $this->Uid();

$sql = $db->query("INSERT INTO walletpoint (id,trno,sin,cos,tan,type,status,stage,remark,ctime,rep,opt,agent) VALUES ('$id','$trno','$sin','$amt','$tan','$type','$status','usd','$remark','$ctime','$identity','$opt','$agent') ") or die(mysqli_error($db));
 
		return;
	}
	   function processWalletPointNaira($id,$amt,$type,$level,$remark,$opt='')
        {
global $db;
$agent = $_COOKIE['agent']??'';
if(sqL1('user','sn',$id)==1){$id = userName2($id,'id'); }

        	$ctime = time();
        	$sin = $this->wallet($id);
		$amt = ($type>10) ? $amt : '-'.$amt; //as cos
		$tan = $sin+$amt;
		$trno = $this->win_hash(12);

		$status = 2; 
		$identity = $this->Uid();

$sql = $db->query("INSERT INTO walletpoint (id,trno,sin,cos,tan,type,status,stage,remark,ctime,rep,opt,agent) VALUES ('$id','$trno','$sin','$amt','$tan','$type','$status','ngn','$remark','$ctime','$identity','$opt','$agent') ") or die(mysqli_error($db));
 
		return;
	}



	function logAgent(){
		global $db,$report,$count;
		$uid = $this->Uid();
		$agent = $_COOKIE['agent']??'';
		$n = sqL2('agent','id',$uid,'agent',$agent);
		$ctime = time();
	if($agent==''){$this->Logout(); /*report device not recognized*/ }
	if($n==0){
		$db->query("INSERT INTO agent (id,ctime,agent) VALUES ('$uid','$ctime','$agent') ");
	}else{
		$freq = sqLx2('agent','id',$uid,'agent',$agent,'freq')+1;
		$db->query("UPDATE agent SET freq='$freq',ctime='$ctime' WHERE agent='$agent' ");
	}
	return;
}

function authorizeDevice(){

}

function logActivity(){
	//log page,activity,device on every page load and action
}
function updateWalletBal(){
	global $db;
	$sql = $db->query("SELECT * FROM user ");
	while ($row = mysqli_fetch_assoc($sql)) {
		$id=$row['id'];
		$db->query("INSERT INTO walletbal (id) VALUES ('$id')");
	}
	return;
}
function walletdebit($id)
{
	global $db;
	$amt = 0;
	$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type<=10 ");
	$row = mysqli_fetch_assoc($sql);
	$amt = $row['value_sum'];
	
	return abs($amt);
}

function walletadmin($sn)
{
	global $db;
	$amt = 0;
	$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE type= '$sn' ");
	$row = mysqli_fetch_assoc($sql);
	$amt = $row['value_sum'];
	return $amt;
}
	  //wallet credit...
function walletcredit($id)
{
	global $db;
	$amt = 0;
	$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type>=6 ");
	$row = mysqli_fetch_assoc($sql);
	$amt = $row['value_sum'];
	
	return abs($amt);
}
     //wallet credit...
function levelPayout()
{
	global $db;
	$amt = 0;
	$sql = $db->query("SELECT SUM(amount) AS value_sum FROM award ");
	$row = mysqli_fetch_assoc($sql);
	$amt = $row['value_sum'];
	
	return abs($amt);
}

function walletbal($id,$sin,$amt,$tan)
{
	global $db;
	$sql = $db->query("UPDATE walletbal SET sin='$sin', cos='$amt', tan='$tan' WHERE id='$id'");   
	return;
}
	//Wallet....
function wallet($id,$opt='')
{
	global $db;

		$amt = 0;
		$sql = ($opt=='') ? $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' ") : $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type='$opt' ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		//return ($amt<0 && $opt==0) ? 0 : $amt;
		return $amt;
}


	//Wallet....
function wallett($id,$opt=0)
{
	global $db;

		$amt = 0;
		$sql = ($opt==0) ? $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' ") : $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type='$opt' ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;
}

function walletnaira($id,$opt='')
{
	global $db;

		$sql = ($opt=='') ? $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' ") : $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' AND type='$opt' ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}
function wallettnaira($id,$opt=0)
{
	global $db;

		$amt = 0;
		$sql = ($opt==0) ? $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' ") : $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' AND type='$opt' ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}
function walletPoint($id)
{
	global $db;

		$amt = 0;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM walletpoint WHERE stage='usd' AND id = '$id' ");

		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}
function walletPointNaira($id)
{
	global $db;

		$amt = 0;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM walletpoint WHERE stage='ngn' AND id = '$id' ");

		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}

function walletPointAll($id)
{  $rate = sqLx('setup','sn',1,'ntod_d');
	$a = $this->walletPoint($id);
	$b = $this->walletPointNaira($id)/$rate;
	$all = $a+$b;
	return $all; 
}
	//Wallet....
function DeductedSav($ref)
{
	global $db;
		$amt = 0;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE opt='$ref' ");

		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;

}


function pendingPay($id)
{
    global $db;
	$val = 0;

    $ref = userName($id, 'sp');
	if($ref > 2) {  $val = 0; }
	else {
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type BETWEEN 10 AND 29 ");
		$row = mysqli_fetch_assoc($sql);
		$val = $row['value_sum'];
	}

	return $val;
}


function pendingWithd($opt=0)
{
	global $db;

	$sql =  $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE type = 1 AND status<2 ");
	$sql2 =  $db->query("SELECT * FROM wallet WHERE type = 1 AND status<2 ");
	$no = mysqli_num_rows($sql2);
	$row = mysqli_fetch_assoc($sql);
	$amt = $row['value_sum'];
	
	return $opt==0 ? $amt : $no;

}

function userIncome($id)
{
	global $db;
	// if(strlen($id)<6){return 0; }else{
	// 	$amt = 0;
	// 	$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND cos>1");
	// 	if(userName($id,'sp')<2){
	// 	$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND cos>1 AND type !BETWEEN 11 AND 14 ");
	// 	}
	// 	$row = mysqli_fetch_assoc($sql);
	// 	$amt = $row['value_sum'];
	// 	return $amt;
	// }
	return 0;
}


function userDebit($id)
{
	global $db;
	if(strlen($id)<6){return 0; }else{
		$amt = 0;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND cos<1");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		return $amt;
	}
}
function cash($id)
	{//tr
		global $db;
		$amt = 0;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type BETWEEN 11 AND 14 ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletRange($id,$x,$y)
	{
		global $db;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletRangeMonth($id,$m,$x,$y)
	{
		global $db;
		//$m = date('Y-'.$m);
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND created LIKE '%$m%' AND type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletRangeNaira($id,$x,$y)
	{
		global $db;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' AND type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletRangeNairaMonth($id,$m,$x,$y)
	{
		global $db;
		//$m = date('Y-'.$m);
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM walletnaira WHERE id = '$id' AND created LIKE '%$m%' AND type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletEarning($id,$x,$y)
	{
		global $db;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE id = '$id' AND cos>0 AND type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}

	function walletRangeAdmin($x,$y)
	{
		global $db;
		$sql = $db->query("SELECT SUM(cos) AS value_sum FROM wallet WHERE type BETWEEN $x AND $y ");
		$row = mysqli_fetch_assoc($sql);
		$amt = $row['value_sum'];
		
		return $amt;
	}
	
	function UnreadMsg()
	{
		global $db;
		$no=0;
		$sql = $db->query("SELECT * FROM user ");
		while($row = mysqli_fetch_assoc($sql)){ $id=$row['id'];
		if($this->userUnreadMsg($id)>0){ $no += 1; }
	}
	return $no;
}
function userUnreadMsg($id)
{
	global $db;

	$sql = $db->query("SELECT * FROM msg WHERE senderid='$id' AND active<2");
	$no = $sql->num_rows;
	return $no;
}  
function msgStatus($sn,$col='active')
{
	global $db;
	$que = $db->query("SELECT * FROM msg WHERE sn = '$sn' ") or die(mysqli_error());
	$ro = mysqli_fetch_array($que);
	return $ro[$col];
}
function userExist($username)
{
	global $db, $report, $count;
	$sql = $db->query("SELECT * FROM user WHERE user = '$username' ") or die(mysqli_error());
	$num = mysqli_num_rows($sql);
	if ($num == 0) {
		$res = FALSE;
	} else {
		$res = TRUE;
	}
	return $res;
}
function userIdExist($id)
{
	global $db, $report, $count;
	$sql = $db->query("SELECT * FROM user WHERE id = '$id' ") or die(mysqli_error());
	$num = mysqli_num_rows($sql);
	if ($num == 0) {
		$res = FALSE;
	} else {
		$res = TRUE;
	}
	return $res;
}


function uidToSn($uid)
{
	global $db;
    	$usersn = $this->sqLz('user', 'id', $uid, 'sn'); //returns the sn 
    	if(empty($usersn)){
    		return FASLE; 
    	}else{
    		return $usersn;  //returns the sn number 
    	}
    }
    function snToID($usersn)
    {
    	global $db;
    	$userid = $this->sqLz('user', 'sn', $usersn, 'id');
    	$id = $this->Uid();
    	$currentuser = ($userid == $id) ? TRUE : FASLE;
    	return $currentuser;
    }
    function idToUser($id, $col = 'user')
    {
    	global $db;
    	$que = $db->query("SELECT * FROM user WHERE id = '$id' ") or die(mysqli_error());
    	$ro = mysqli_fetch_array($que);
    	return $ro[$col];
    }
    function userToId($user, $col='id')
    {
    	global $db;
    	$que = $db->query("SELECT * FROM user WHERE user = '$user' ") or die(mysqli_error());
    	$ro = mysqli_fetch_array($que);
    	return $ro[$col];
    }
    function SupportTicket()
	{//CTIME
		global $db, $report;
		$msg = addslashes(sanitize($_POST['msg']));
		$ctime = time();
		$id = $this->Uid();
		$msg = $db->query("INSERT INTO msg (senderid,receiverid,msg,ctime)
			VALUES('$id','1','$msg','$ctime')") or die(mysqli_error());
		$report = 'Message sent Successfully, You will get a response soon';
		return;
	} 
	function SupportTicket2()
	{
		global $db,$report;
		$id=$this->userToId($_GET['user']);
		$msg = addslashes(sanitize($_POST['msg']));
		$ctime = time();
		$msg = $db->query("INSERT INTO msg (senderid,receiverid,msg,ctime)
			VALUES('1','$id','$msg','$ctime')") or die(mysqli_error());
		$report = 'Message sent Successfully';
		return;
	} 
	function check_login(){
		if(!isset($_SESSION['user_id'])){
			header('location: login.php'); 
			exit;
		}
		return;
	}
	function EditProfile(){
		global $db;
		$_SESSION['sn'] = $_POST['EditProfile']; 
		return; 
	}
	function EditUser(){
		global $db;
		$_SESSION['fid'] = $_POST['EditUser'];
		header("location: userprofile.php");
		return;
	}

	function VerifySponsor()
	{
		global $db, $report, $count;
		$sponsor = $_POST['username']??'';
		$username = $_SESSION['username']??'';
		//i don't have a sponsor
		$nosponsor = $_POST['nosponsor']??'';
		if(empty($nosponsor) && empty($sponsor)){
			header('location: sponsor.php');
			$report = 'Enter Sponsor or tick I dont have sponsor'; $count=1;
		}

		if($sponsor == $username){
			$report = "You can't Sponsor yourself";
			$count = 1;
		}
		elseif($sponsor != $username && $sponsor != ''){
			$sql = $db->query("SELECT * FROM user WHERE user='$sponsor' LIMIT 1");
			$result = $sql->fetch_assoc();
			
			if($sql->num_rows == 1 AND !is_null($result['package'])){
				$sponsorid = $result['sn'];
				$query = $db->query("UPDATE user SET sponsor = '$sponsorid' WHERE user= '$username'");
				$_SESSION['report1'] = "Congratulation!! Sponsor Verified. Please Login";
				header('location: login.php');
			}else{
				$report  = "Invalid Sponsorid";
				$count = 1;
			}
		}
		elseif($nosponsor == 'nosponsor'){
			$sqlquery = $db->query("UPDATE user SET sponsor = 1 WHERE user='$username'");
			$_SESSION['report1'] = "Congratulation!! Sponsor Verified. Please Login";
			header('location: login.php');
		}
		return ;
	}
	
	function VerifyUser()
	{
		global $db, $report, $count;
		$rec = $_POST['rec']??'';
		if(sqL1('user','user',$rec)==1){
			$rec = sqLx('user','user',$rec,'id');
			if($rec==$this->Uid()){
				$report = 'Invalid Username. Try again';	$count=1;
			}else{
				$_SESSION['rec'] = $rec;
				$report = 'Username successfully verified';
			}
		}
		else{
			$report = 'Invalid Username. Try again';	$count=1;
		}
		return ;
	}
	


	function StartSignup(){
		global $db, $report, $count;
		$firstname = sanitize($_POST['firstname']);
		$lastname = $_POST['lastname']??'';
		$email = sanitize($_POST['email']);
		$phone = sanitize($_POST['phone']);
		//$sex = sanitize($_POST['sex']);
		$ref =  strtolower(sanitize($_POST['ref']));
		$upline =  strtolower(sanitize($_POST['upline']));
		if(sqL1('user','user',$upline)==0){$upline=$ref; }
		$password = sanitize($_POST['password']);
		$password2 = sanitize($_POST['password2']);
		$pass = password_hash($password, PASSWORD_BCRYPT);
		$username = strtolower(clean($_POST['username'])); 

		if(sqL1('user','user',$ref)==0){ $ref=strtolower(sqLx('user','sn',1,'user')); }
		if(sqLx('user','user',$ref,'stage')==0){$ref = strtolower(sqLx('user','sn',1,'user'));}

		if(sqL1('user','user',$upline)==0){ $upline=strtolower(sqLx('user','sn',1,'user')); }
		if(sqLx('user','user',$upline,'stage')==0){$upline = strtolower(sqLx('user','sn',1,'user'));}

		if(sqL1('user','user',$username)==1){ $report = 'This username already exist, try another one '; $count=1; return; }
		if($password!=$password2){ $report = 'Password miss-match'; $count=1; return; }
		// if(sqL1('user','email',$email)==1){ $report = 'This E-mail already exist, try another one '; $count=1; return; }
		if(strlen($password)<6){$report = 'Password too short. Password must not be less than 6 characters'; $count=1; return; }



		$ctime = time();
		$id = 'f'.$this->win_hashs(9);
		
$sql = $db->query("INSERT INTO user(id,firstname,lastname,email,phone,user,pass,sponsor,upline)
			VALUES('$id','$firstname','$lastname','$email','$phone','$username','$pass','$ref','$upline')") or die('Cannot Connect to Server'); 

		$report = 'Registration Successful.';
		$this->emailerAllNew($email,$firstname); //Welcome e-mail
		$_SESSION['user_id'] = $id;
header('location: ./');
		
		return;
	}


	function bonus($level, $opt='amount')
	{
		return sqLx('levelbonus', 'level', $level, $opt);
	}


// function payPairingBonus($sponsorid,$e)
// {
// 	global $db;
// 	$stage = userName2($sponsorid,'stage');
// 	$stageteam = $this->stageTeam($sponsorid);
// 	$matrix = sqLx('levelbonus','stage',$stage,'matrix')/3;
// 	$opt = $sponsorid.'-'.$stage.'-'.$stageteam;
// 	if($stageteam==2 AND sqL1('wallet','opt',$opt)==0){ 
// 	$this->processWallet($sponsorid,$matrix,12,$stage,'Stage '.$stage.', 1st Pairing Bonus',$opt); /*Pay 1st*/ }
// 	elseif($stageteam==4 AND sqL1('wallet','opt',$opt)==0){
// 	$this->processWallet($sponsorid,$matrix,12,$stage,'Stage '.$stage.', 2nd Pairing Bonus',$opt);  /*Pay 2nd*/ }
	
// }


	// function payAllBonusses($sponsor,$stage)
	// {	
	// 	global $db, $report, $count;

	// 	$sql = $db->query("SELECT * FROM levelbonus WHERE stage = '$stage' ");
	// 	$row = mysqli_fetch_assoc($sql);
	// 	$incentive = $row['incentive'];
	// 	$payout = $row['stepout'];
	// 	$matrix = $row['matrix']/3;
	// 	$item = $row['item'];
	// 	$sl = 'Stage '.$stage;
	// 	$stageteam = $this->stageTeam($sponsor);
	// 	$opt = $sponsor.'-'.$stage.'-6';
	// 	$trn = $this->win_hash(10);
	// 	//$id = $this->keyToId($sponsor);
	// 	// if($row['stagelevel']==0){$sl = 'Stage '.($row['stage']-1).' Level 2';}
	// 	// if($matrix > 0) {
	// 	// 	$this->processWallet($sponsor,$matrix,12,$stage,$sl.' Pairing Bonus','bonuses');
	// 	// }
	// 	//if(sqL('wallet','opt',$opt)==0){
	// $this->processWallet($sponsor,$matrix,12,$stage,'Stage '.$stage.', 3rd Pairing Bonus',$opt);  /*Pay 3rd*/  //}

	// 	if($payout > 0) { 
	// 		$this->processWallet($sponsor,$payout,13,$stage,$sl.' Food & Cash Bonus','bonuses');
	// 	}
	// 	if($incentive > 0) {
	// 		$this->processWallet($sponsor,$incentive,14,$stage,$sl.' Incentive Bonus: N'.number_format($incentive).' '.$item,$trn);
	// 		$db->query("UPDATE wallet SET status=1 WHERE opt='$trn' ");
	// 	}
	// 	return;
	// }



// 	function signupUserIni($pin)
// 	{
// 		global $db, $report, $count, $uri;

// 		$firstname = $_SESSION['firstname'];
// 		$lastname =$_SESSION['lastname'];
// 		$email = $_SESSION['email'];
// 		$phone = $_SESSION['phone'];
// 		$user = strtolower($_SESSION['username']);
// 		$user = clean(strtolower($user));
// 		$password  = $_SESSION['password'];
// 		$pass = password_hash($password, PASSWORD_BCRYPT);
// 		//$sex  = $_SESSION['sex'];
// 		$sp  = $_SESSION['ref'];
// 		$sponsor  = sqLx('user','user',$sp,'sn');
		

// 		$g = sqLx('user','sn',$sponsor,'g')+1;
// 		$ctime = time();
// 		$id = 'u'.$this->win_hashs(8);
		
// $sql = $db->query("INSERT INTO user(id,firstname,lastname,email,phone,user,pass,sponsor,g,pin)
// 			VALUES('$id','$firstname','$lastname','$email','$phone','$user','$pass','$sponsor','$g','$pin')") or die('Cannot Connect to Server'); 
// 	$db->query("UPDATE pin SET id='$id', used='$ctime', status=1 WHERE pin='$pin'");
// 		unset($_SESSION['signup']);
// 		$report = 'Registration Successful.';
// 		$this->emailerAllNew($email,$firstname); //Welcome e-mail

// $sp = sqL1('user','sponsor',$sponsor);
// $this->processWallet($sponsor,12,11,0,'Referral Bonus',$id);	//pay referal bonus
// $db->query("UPDATE user SET sp='$sp' WHERE sn='$sponsor' "); //update sponsor
// $ctime = time();


// $arr = [2,4,6];
// $sponsorid = $sponsor;		
// if(in_array($sp, $arr)){
// 	$i=1;
// 	while($i<6){$e=$i++;
// 		$this->payPairingBonus($sponsorid,$e);
// 		$sponsorid = sqLx('user','sn',$sponsorid,'sponsor');
// 		if($sponsor==0){$i=6;}
// 			   }
// 		  }

		
// if($sp==6){
// 	$i=1;
// 	while($i<6){$e=$i++;
// 		$this->getPromoted($sponsor,$e);
// 		$sponsor = sqLx('user','sn',$sponsor,'sponsor');
// 		if($sponsor==0){$i=6;}
// 			   }
// 		  }
	
// 	if($uri=='register'){
// 	    $report = 'New user successfully registered: '.userName($id).'<br>Username: '.$user.', Password: '.$password;
// 	    return;
// 	}else{
// 	    $_SESSION['user_id']=$id;
// 	  header('location: account/');  
// 	}
	
	
// 		return;
// 	}


// function getPromoted($sponsor,$stage){
// 	global $db;
// $sql = $db->query("SELECT * FROM user WHERE sponsor='$sponsor' AND stage>='$stage' ");
// if(mysqli_num_rows($sql)==6){
// 	$team = array(); 
// 	while($row=mysqli_fetch_assoc($sql)){$team[] = $row['sn']; }
// 	$stageTeam = json_encode($team);
// 	$newstage = $stage+1;   
// 	$db->query("UPDATE user SET stage='$newstage' WHERE sn='$sponsor' "); //update new stage
// 	$db->query("INSERT INTO stageteam (sponsor,stage,team) VALUES ('$sponsor','$stage','$stageTeam')"); //log new stage and team
// 	$this->payAllBonusses($sponsor, $stage); //Pay stage bonuses
// }
// return; 
// }



// 	function RegisterAuto($sponsor)
// 	{
// 		global $db, $report, $count;

// 		$sql = $db->query("SELECT * FROM user WHERE sn = $sponsor ") or die(mysqli_error());

// 		$row = mysqli_fetch_array($sql);

// 	//	$sql2 = $db->query("SELECT sn FROM user WHERE sponsor = $sponsor ") or die(mysqli_error());
// 		$ct = sqL1('user','sponsor',$sponsor)+1;

// 		$firstname = $row['firstname'];
// 		$lastname = $row['lastname'];

// 		$phone = $row['phone'];
// 		$email = $row['email'];

// 		$sex = $row['sex'];
// 		$state = $row['state'];
// 		$address = $row['state'];
// 		$country = $row['country'];
// 		$pass = $row['pass'];
// 		$user = $row['user'].'x'.$ct;
// 		$g = $row['g']+1;


// 		$id = 'a'.$this->win_hashs(8);
// 		$sql = $db->query("INSERT INTO user(id,firstname,lastname,email,phone,sex,user,pass,sponsor,g)
// 			VALUES('$id','$firstname','$lastname','$email','$phone','$sex','$user','$pass','$sponsor','$g')") or die('Cannot Connect to Server'); 
// 	//	unset($_SESSION['signup']);


// $sp = sqL1('user','sponsor',$sponsor);
// $this->processWallet($sponsor,12,11,0,'Referral Bonus',$id);	//pay referal bonus
// $db->query("UPDATE user SET sp='$sp' WHERE sn='$sponsor' "); //update sponsor
// $ctime = time();



// $arr = [2,4,6];
// $sponsorid = $sponsor;		
// if(in_array($sp, $arr)){
// 	$i=1;
// 	while($i<6){$e=$i++;
// 		$this->payPairingBonus($sponsorid,$e);
// 		$sponsorid = sqLx('user','sn',$sponsorid,'sponsor');
// 			   }
// 		  }

		
// if($sp==6){
// 	$i=1;
// 	while($i<6){$e=$i++;
// 		$this->getPromoted($sponsor,$e);
// 		$sponsor = sqLx('user','sn',$sponsor,'sponsor');
// 		if($sponsor==0){return; }
// 			   }
// 		  }
// 		return;
// }





	// function updateLevel($sn){
	// 	global $db;
	// 	$key = $sn;  
	// 	$i=1;
	// 	while($i<5){ $e=$i++; 
	// 		$sn = sqLx('user','sn',$sn,'a1');
	// 		$stage = sqLx('user','sn',$sn,'stage');
	// 		if($sn>0 AND $stage>1){
	// 			$this->promoteUser($sn,$stage);

	// 		}else{return; }
	// 	}
	// 	return;
	// }



// 	function promoteUser($sn,$stage){
// 		global $db;
// 		$ulevel = sqLx('user','sn',$sn,'level');
// 		$base = $this->stageToEven($stage);  
// 		$team = $this->stageTeam($sn);
// 		$level = $ulevel;
// 		if($team==14){$level=$base+3; $stage=$stage+1;}elseif($team>11){$level=$base+2;}elseif($team>2){$level=$base+1;}

// 		if($level>$ulevel){$db->query("UPDATE user SET level='$level',stage='$stage' WHERE sn='$sn' "); 
// 		$id = userName2($sn,'id');
// 		if($level==6){$this->processWallet($sn,25,14,$stage,'Food Voucher',$id); }
// 		if($level==7){$this->processWallet($sn,125,14,$stage,'Smart Phone Incentive',$id); $this->processWallet($sn,25,14,$stage,'Food Voucher',$id); $this->processWallet($sn,250,14,$stage,'Laptop Incentive',$id); }
// 		if($level==9){$this->processWallet($sn,125,14,$stage,'Welfare Fund',$id); }
// 		if($level==10){$this->processWallet($sn,1250,14,$stage,'International Trip',$id); }
// 		if($level==5 OR $level==8 OR $level==11){ $this->payStageBonuses($sn,$stage); }
// 	}

// }




// function payStageBonuses($sn,$stage){
// 	//user bonus = incentive + stepout bonuses
// 	$ssn = $sn; $userbonus3=0;
// 	if($stage==3){$userbonus=13.75; $userbonus2= 7.5; $upbonus = 15; }elseif($stage==4){$userbonus = 6250; $userbonus2 = 125; $userbonus3 = 125; $upbonus = 175; }elseif($stage==5){$userbonus = 12500; $upbonus = 1000; }
// 	$id = userName2($sn,'id'); 
// 	$level = userName2($sn,'level');  $stt = $stage-1;
// 	$this->processWallet($sn,$userbonus,13,$stt,'Stage '.$stt.' Stepout Bonus',$id);
// 	$this->processWallet($sn,$userbonus2,13,$stt,'Stage '.$stt.' Stepout Bonus',$id);
// 	if($userbonus3>0){$this->processWallet($sn,$userbonus3,13,$stt,'Stage '.$stt.' Stepout Bonus',$id); }
// 	$team = $this->stageTeam($sn);
// 	if($team>0){$pbonus = $team*$upbonus; $this->processWallet($sn,$pbonus,12,$stage,'Stage '.$stage.' Matrix Bonus',$id);  }
// 	$i=1;  $lim = $stage==3 ? 4 : 3;
// 	while($i<=$lim){$e=$i++; 
// 		$sn = sqLx('user','sn',$sn,'a1'); $level = userName2($sn,'level');  $snstage = sqLx('user','sn',$sn,'stage'); 
// 		if($sn>0 AND $snstage==$stage){$this->processWallet($sn,$upbonus,12,$snstage,'Stage '.$stage.' Matrix Bonus',$id);  }
// 	}

// 	return;
// }


// function userTeam($sn){
// 	global $db;
// 	$sql = $db->query("SELECT * FROM user WHERE sponsor='$sn' "); 
// 	return mysqli_num_rows($sql);
// }




// function stageLeg($sn){
// 	global $db;
// 	$stage = userName2($sn,'stage');

// 	$team = array(); 
// 	$sql = $db->query("SELECT * FROM user WHERE sponsor='$sn' AND stage>='$stage' LIMIT 6 "); 
// 	while($row = mysqli_fetch_assoc($sql)){$team[] = $row['sn'];  }
// 	return $stageTeam = json_encode($team); 
// }

function userLegs($key){
global $db;
$team = array(); 
	$sql = $db->query("SELECT * FROM user WHERE a1='$key' "); 
	while($row = mysqli_fetch_assoc($sql)){$team[] = $row['sn'];  }
	return $team; 
}
//
function legStageTeam($key,$stage){
	global $db; //
$sql = $db->query("SELECT * FROM user WHERE stage>='$stage' AND pack=50 AND (sn='$key' OR a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') ORDER BY joined ASC LIMIT 7");
return mysqli_num_rows($sql);
}

//
function totalPackStageTeam($key,$stage,$pack){
	global $db;
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	if($key==0 OR empty($key)){return 0;}
$sql = $db->query("SELECT * FROM user WHERE pack>='$pack' AND $stg>='$stage' AND (a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') LIMIT 14 ");
return mysqli_num_rows($sql);
}

function totalPackTeam($key,$pack){
	global $db;
	if($key==0 OR empty($key)){return 0;}
$sql = $db->query("SELECT * FROM user WHERE pack>='$pack' AND (a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') ");
return mysqli_num_rows($sql);
}
//
function totalPackTeamLeg($key,$pack,$limit=5000){
	global $db;
	if($key==0 OR empty($key)){return 0;}
$sql = $db->query("SELECT * FROM user WHERE pack>='$pack' AND (a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR sn='$key') LIMIT $limit ");
return mysqli_num_rows($sql);
}

function totalStageTeamReq($key,$pack,$limit){
$legs = $pro->userLegs($key); $l =  $legs[0]; $r= $legs[1];
$x = $this->totalPackTeamLeg($l,$pack,$limit) + $this->totalPackTeamLeg($r,$pack,$limit);
return $x;
}

//
function legStageTeamx($key,$stage){
	global $db;
$sql = $db->query("SELECT * FROM user WHERE stage>='$stage' AND (sn='$key' OR a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') ORDER BY joined ASC LIMIT 7");
return mysqli_num_rows($sql);
}

function allTeam($key){
	global $db;

$sql = $db->query("SELECT * FROM user WHERE a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key' ");
return mysqli_num_rows($sql);
}


function stageTeamHeads($key,$stage,$pack){
	global $db; 
	//$stg = sqLx('user','sn',$key,'stage');
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;
	$legs = $this->userLegs($key);
	$head = array();
	//if($stg>=$stage){$head[] = $key;  }
	$i=0;
	while($i<count($legs)){$e=$i++; 
$key = $legs[$e];
$sql = $db->query("SELECT * FROM user WHERE $stg>='$stage' AND pack>=$pack AND (sn='$key' OR a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') ORDER BY joined ASC LIMIT 7");
while($row=mysqli_fetch_assoc($sql)){$head[]=$row['sn']; }
	}

	return $head;
}


function stageTeamHeadsGen1($key,$stage,$pack){
	global $db; 
	//$stg = sqLx('user','sn',$key,'stage');
	$legs = $this->userLegs($key);
	$head = array();
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;

$sql = $db->query("SELECT * FROM user WHERE $stg>='$stage' AND pack>='$pack' AND (sn='$key' OR a1='$key') ORDER BY joined ASC LIMIT 3");
while($row=mysqli_fetch_assoc($sql)){$head[]=$row['sn']; }
	

	return $head;
}


function stageTeamHeadsGen($key,$stage,$pack){
	global $db; 
	//$stg = sqLx('user','sn',$key,'stage');
	$legs = $this->userLegs($key);
	$head = array();
	$stg = $pack==5 ? 'stage' : 'stage'.$pack;

$sql = $db->query("SELECT * FROM user WHERE $stg>='$stage' AND pack>='$pack' AND (sn='$key' OR a1='$key' OR a2='$key' OR a3='$key' OR a4='$key' OR a5='$key' OR a6='$key' OR a7='$key' OR a8='$key' OR a9='$key' OR a10='$key' OR a11='$key' OR a12='$key' OR a13='$key' OR a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key' OR a19='$key' OR a20='$key' OR a21='$key' OR a22='$key' OR a23='$key' OR a24='$key' OR a25='$key' OR a26='$key' OR a27='$key' OR a28='$key' OR a29='$key' OR a30='$key' OR a31='$key' OR a32='$key' OR a33='$key' OR a34='$key' OR a35='$key' OR a36='$key' OR a37='$key' OR a38='$key' OR a39='$key' OR a40='$key' OR a41='$key' OR a42='$key' OR a43='$key' OR a44='$key' OR a45='$key' OR a46='$key' OR a47='$key' OR a48='$key' OR a49='$key' OR a50='$key') ORDER BY joined ASC LIMIT 7");
while($row=mysqli_fetch_assoc($sql)){$head[]=$row['sn']; }
	

	return $head;
}


function packStageTeam($uidx,$stage,$pack){
global $db; 

$head = array();
$c = 0;
$sql = $db->query("SELECT * FROM user WHERE a1='$uidx' ");
      while($row=mysqli_fetch_assoc($sql)){

$x = $this->stageTeamHeadsGen($row['sn'],$stage,$pack);
$c+=count($x);

}
return $c;
}


function teamHeads($uidx,$stage){
global $db; 

$head = array();
$sql = $db->query("SELECT * FROM user WHERE a1='$uidx' ");
      while($row=mysqli_fetch_assoc($sql)){

$x = $this->stageTeamHeadsGen($row['sn'],$stage);
$i = 0;
$c=count($x);
//if($c==7){$this->logHeads($uidx,$x);}
//if($c>7){$c=7;} 
while($i<$c){$e=$i++;
    $head[]=$x[$e]; 
}
}
return $head;
}

function stage1TeamHeads($key){
	global $db; 
	
	$head = array();

$sql = $db->query("SELECT * FROM user WHERE stage>=1 AND (sn='$key' OR a1='$key')");
while($row=mysqli_fetch_assoc($sql)){$head[]=$row['sn']; }
	return $head;
}

function stage1Team($key){
	global $db; 
	
	$head = array();

$sql = $db->query("SELECT * FROM user WHERE stage>=1 AND (a1='$key' OR a2='$key')");
while($row=mysqli_fetch_assoc($sql)){$head[]=$row['sn']; }
	return $head;
}
//vip team
function stageTeam($key,$stage=''){
	$stage = $stage=='' ? userNameSn($key,'stage') : $stage;
	$legs = $this->userLegs($key);
	$team = 0;
	$i=0;
	while($i<count($legs)){$e=$i++;
$leg = $legs[$e];
$team += $this->legStageTeam($leg,$stage);
	}

	return $team;
}
//all team
function stageTeamx($key){
	$stage = userNameSn($key,'stage');
	$legs = $this->userLegs($key);
	$team = 0;
	$i=0;
	while($i<count($legs)){$e=$i++;
$leg = $legs[$e];
$team += $this->legStageTeamx($leg,$stage);
	}

	return $team;
}


function gFirst(){
	global $db;
	$x='';
	$i=1; while($i<12){ $e=$i++;
		$sql = $db->query("SELECT * FROM user WHERE g='$e' ORDER BY sn ASC LIMIT 1 ");
		$row = mysqli_fetch_assoc($sql);
		$x .= $row['sn'].', ';
	}
	return $x; 
}

function StageSk(){
	$_SESSION['stage'] = $_POST['StageSk'];
}

function stageToEven($stage){

	if($stage==7){$bl=17;}
	elseif($stage==6){$bl=14;} 
	elseif($stage==5){$bl=11;}
	elseif($stage==4){$bl=8;}
	elseif($stage==3){$bl=5;}
	elseif($stage==2){$bl=2;}
	elseif($stage==1){$bl=0;}
	else{$bl=0;}
	return $bl; 
}






function redirctInactive()
{global $uri;
$id =$this->Uid();
$stage = userName($id,'stage');
$arr = ['index','fundwallet','listedproperties','listedproperties2','propertyinfo','propertyinfo2','subscriptionplans','cycleinvestment','cycleinvestment2','revpropertyinfo','revpropertyinfo2','login','register','myprofile','groupinvestment','groupinvestment2','receipt','receipt','fundconvert'];	
if(in_array($uri, $arr) OR $stage>0){}else{header('location: ./index'); exit;  }

return;
}



function updateSponsors(){
	global $db;

	$i=1;
	$sql = $db->query("SELECT * FROM user ");
	while($row = mysqli_fetch_array($sql)){ $sn = $row['sn']; $sp = sqL1('user','sponsor',$sn);  
	$db->query("UPDATE user SET sp='$sp' WHERE sn='$sn' ");
}
return;
}

function updateActive(){
	global $db;

	$i=1;
	$sql = $db->query("SELECT * FROM user ");
	while($row = mysqli_fetch_array($sql)){ $sn = $row['sn'];  
	$act = sqL1('user','a1',$sn);
	$db->query("UPDATE user SET active='$act' WHERE sn='$sn' ");
}
return;
}


function updateAllUplines(){
	global $db;
	if(sqL1('user','a1',0)>0){
		$sql = $db->query("SELECT * FROM user WHERE a1=0 ");
		while($row = mysqli_fetch_array($sql)){ $sn = $row['sn'];
		$this->updateUplines($sn);
	}
}
return;
}	

function LoginUsers()
{
	
	global $db, $report, $count;
	$username = strtolower(sanitize($_POST['username']));
	$password = $_POST['password'];

	$sql = $db->query("SELECT * FROM user WHERE user='$username' ");
	if (mysqli_num_rows($sql) != 1){
		$report = 'Invalid Login details, Try again.'; $count = 1; return; 
	                               }

		$row = mysqli_fetch_array($sql);
			$status = $row['status'];
if($status==0){$report = 'Account Inactive. Contact System Admin'; $count = 1; return; }
if(password_verify($password, $row['pass'])) {
			$_SESSION['user_id'] = $row['id'];
			$this->logAgent();
			header('location: ./');   
		}else {
		$report = 'Invalid Login details, Try again';
		$count = 1;	
		}

	return;
}





function Logout(){
	//$_SESSION['report'] = "You have logged out successfully";
	//unset($_SESSION['user_id']);
	session_destroy(); 
	header('location: login.php');
	return;
}
function Uid(){
	$uid = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
	return $uid;
}
function Fid(){
	$fid = $_SESSION['fid']??0;
	return $fid;
}
function win_hashs($length){
	return substr(str_shuffle(str_repeat('123456789abcdefghijklmnopqrstuvwxyz', $length)), 0, $length);
}
function valEmpty($field, $fname)
{
	global $report, $count;
	$field = sanitize(trim($field));
	if ($field == '') {
		$report .= "<br>" . $fname . " field is required! ";
		$count = 1;
		return;
	} elseif (strlen($field) < 3) {
		$report .= "<br>" . $fname . " entered is too short! ";
		$count = 1;
		return;
	} else {
		return $field;
	}
}
function valPass($field)
{
	global $report, $count;
	if ($field == '') {
		$report .= "<br>Password field is required! ";
		$count = 1;
		return;
	} elseif (strlen($field) < 4) {
		$report .= "<br>Password cannot be less than 6 characters! ";
		$count = 1;
		return;
	} else {
		return sanitize($field);
	}
	}// end of a Valpass

	function valPhone($field)
	{
		global $db, $report, $count;
		$field = sanitize(trim($field));
		$query =$db->query("SELECT * FROM user");
		$result = $query->fetch_assoc();
		if($result['phone'] == $field){
			$report = 'This phone number is already existing';
			$count = 1;
		}
		elseif($field == '') {
			$report .= "<br>Phone Number field is required! ";
			$count = 1;
			return;
		} elseif(strlen($field) < 11) {
			$report .= "<br>Phone Number entered is invalid! ";
			$count = 1;
			return;
		} else {
			return $field;
		}
	}

	function myTeam($sn){
		global $db;
		$t=$sn;
		$sql=$db->query("SELECT * FROM user WHERE sponsor='$sn' " )or die(mysqli_error());
		while($row=mysqli_fetch_array($sql)){ 
			$t .= $row['sn'].',';

		}
		return $t;
	}


	//AdminUser update access....
	function UpdateAdminInfo()
	{
		global $db, $report, $count;

		$id = $_SESSION['sn'];
		$firstname = sanitize($_POST['firstname']);
		$lastname = sanitize($_POST['lastname']);
		$username = sanitize($_POST['username']);
		$email = sanitize($_POST['email']);
		$phone = sanitize($_POST['phone']);
		$sex = sanitize($_POST['sex']);
		$dob = sanitize($_POST['dob']);
		$city = sanitize($_POST['city']);
		$address = sanitize($_POST['address']);
		$state = sanitize($_POST['state']);
		$country = sanitize($_POST['country']);
		$bank = sanitize($_POST['bank']);
		$accname = sanitize($_POST['accname']);
		$accno = sanitize($_POST['accountno']);

		$query = ("UPDATE user SET firstname='$firstname', lastname='$lastname', 
			email='$email', phone='$phone', sex='$sex', dob='$dob', city='$city', address='$address', 
			states='$state', country='$country', bank='$bank', accountno='$accno', accname='$accname',
			user='$username'
			WHERE sn='$id'") or die('error');

		if ($db->query($query) === TRUE) {
			unset($_SESSION['sn']);
			$report = "Profile Updated Successfully";
		}else{
			$report = "Invalid data submitted!! please try again.";
			$count = 1;   
		}
		return; 

	}
	#User additional details update
	function UpdateUserDetails(){
		global $db, $report, $count;
		$id = $_SESSION['sn'];
		
		$address = sanitize($_POST['address']);
		$city = sanitize($_POST['city']);
		$dob = sanitize($_POST['dob']);
		$bank = sanitize($_POST['bank']);
		$accname = sanitize($_POST['accname']);
		$accno = sanitize($_POST['accountno']);
		
		$query = ("UPDATE user SET dob='$dob', address='$address', city='$city', bank='$bank', accountno='$accno', accname='$accname' WHERE sn='$id'") or die('error');
		if($db->query($query) === TRUE) {
			unset($_SESSION['sn']);
			$report = "Profile updated successfully"; 
		}
		else{
			$report = "Profile not Updated Successfully";
			$count = 1;   
		}
		return; 

	}
	#User additional details update
	function UpdateBank(){
		global $db, $report, $count;
		$uid = $this->Uid();
		
		$bank = sanitize($_POST['bank']);
		$accname = sanitize($_POST['accname']);
		$accountno = sanitize($_POST['accountno']);
		$wallet = sanitize($_POST['wallet']);
		
		
		$sql = $db->query("UPDATE user SET bank='$bank', accountno='$accountno', wallet='$wallet', accname='$accname' WHERE id='$uid' ") or die('error');

		$report = "Profile information updated successfully"; 
		
		return; 

	}	


	function UpdatePropertyPricing(){
		global $db, $report, $count;
		$uid = $this->Uid();
$ref = $_GET['ref'];		
extract($_POST);
$a1 = sqLx('ginvest','ref',$ref,'amount');		
		
		$sql = $db->query("UPDATE ginvest SET a1='$a1', b1='$b1', b2='$b2', c1='$c1', c2='$c2', d1='$d1', d2='$d2', e1='$e1', e2='$e2', f1='$f1', f2='$f2', fl1='$fl1', fl2='$fl2', fl3='$fl3', com='$com', com2='$com2' WHERE ref='$ref' ") or die('error');

		$report = "Pricing information updated successfully"; 
		
		return; 

	}

	#User additional details update
	function UpdateAddress(){
		global $db, $report, $count;
		$uid = $this->Uid();
		
		//$bank = sanitize($_POST['bank']);
		$address = sanitize($_POST['address']);
		$country = sanitize($_POST['country']);
		
		
		$sql = $db->query("UPDATE user SET address='$address', country='$country' WHERE id='$uid' ") or die('error');

		$report = "Profile information updated successfully"; 
		
		return; 

	}

	#User additional details update
	function UpdateUserData(){
		global $db, $report, $count;
		$fid = $this->Fid();
		
		//$bank = sanitize($_POST['bank']);
		$firstname = sanitize($_POST['firstname']);
		$lastname = sanitize($_POST['lastname']);
		$user = sanitize($_POST['user']);
		$email = sanitize($_POST['email']);
		$phone = sanitize($_POST['phone']);

		if(sqL1('user','user',$user)>0){
			$report = 'The username you entered already exist, try another'; $count=1; return;
		}
		
		
		$sql = $db->query("UPDATE user SET firstname='$firstname', lastname='$lastname', user='$user', phone='$phone', email='$email' WHERE id='$fid' ") or die('error');

		$report = "Profile information updated successfully"; 
		
		return; 

	}

	function stageHead($legs,$n,$stage){
		$num = count($legs);
	if($num<=$n){$x = 'x.jpg'; $y = '';
$z = '';
}
	else{
	$x = 'u'.$stage.'.png';
	$y = userNameSn($legs[$n],'user');
	$z = $this->typeTitle(userNameSn($legs[$n],'pack'));
	}
	return $stage>2 ? '<span><a href="?user='.$y.'"><img src="uploads/'.$x.'"></a><br>'.$y.'</span>' : '<span><a href="?user='.$y.'"><img src="uploads/'.$x.'"></a><br>'.$y.'<br>['.$z.']</span>';
	}


	function stageHead1($stage){
	return 'u'.$stage.'.png';
	}
	

	function sendToAllEmail()
	{

		global $db,$report;

		$message = addslashes($_POST['message']);
		$subject = $_POST['subject'];

		if(empty($message)){
			$report = "Compose your message before pressing the submit button";
			$count = 1;
         //style the $subject variable for the message look beautiful..
		}else{
			$i=1;
			$sql=$db->query("SELECT * FROM user")or die(mysqli_error());
			while($row=mysqli_fetch_array($sql)){ 
				$e=$i++;
				$email = $row['email'];
				$this->emailer($email,$message,$subject);
			}
			$report = 'Email Message successfully sent to all clents: '.$e.' recipients';
		}
		return;
	}
	
	function emailer($email, $message, $subject)
	{
		global $firstname;
		$headers = 'From:   Fination Global <support@finationglobal.com>' . "\r\n";
		$headers .= 'Reply-To: support@finationglobal.com' . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

		$send = mail($email, $subject, $message, $headers);
		return;
	}

	function emailerAllNew($email,$name)
	{   
		$headers = 'From:  Fination Global <support@finationglobal.com>' . "\r\n";
		$headers .= 'Reply-To: support@finationglobal.com' . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

		$subject = 'Welcome to Fination Global';
		$mailmessage = "<p>Welcome " . ucwords($name) . '!<br>
		Congratulation! You have successfully signed up with Fination Global.<br>
		Fination Global is a community of Entrepreneurs, inspired and motivated enough to create wealth for themselves and to help others achieve same. <br>Fination Global is a  company that offers people the opportunity scale up their finances and invest securely in Real Estate and other valuable properties. <br><br>By simply promoting the company and its services you can earn money to become financially independent and able to take care of your financial needs with ease.<br><br>
			
		<br><br>
		Login to your account using your username and password at
		https://finationglobal.com/login </p>';
		$send = mail($email, $subject, $mailmessage, $headers);
		return;
	}


	function emailerAl($email,$username,$password)
	{
		
		$headers = 'From: '.EMAIL_FROM_NAME.' <'.EMAIL_FROM_ADDR.'>' . "\r\n";
		$headers .= 'Reply-To: '.EMAIL_FROM_ADDR . "\r\n";
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: text/html; charset=UTF-8\r\n";


		$subject = 'WELCOME TO '.BUSINESS_NAME;
		$mailmessage = 
		'<!doctype html>
		<html>
		<head>
		<meta name="viewport" content="width=device-width">
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Simple Transactional Email</title>
		<style>
		/* -------------------------------------
		INLINED WITH htmlemail.io/inline
		------------------------------------- */
		/* -------------------------------------
		RESPONSIVE AND MOBILE FRIENDLY STYLES
		------------------------------------- */
		@media only screen and (max-width: 620px) {
			table[class=body] h1 {
				font-size: 28px !important;
				margin-bottom: 10px !important;
			}
			table[class=body] p,
			table[class=body] ul,
			table[class=body] ol,
			table[class=body] td,
			table[class=body] span,
			table[class=body] a {
				font-size: 16px !important;
			}
			table[class=body] .wrapper,
			table[class=body] .article {
				padding: 10px !important;
			}
			table[class=body] .content {
				padding: 0 !important;
			}
			table[class=body] .container {
				padding: 0 !important;
				width: 100% !important;
			}
			table[class=body] .main {
				border-left-width: 0 !important;
				border-radius: 0 !important;
				border-right-width: 0 !important;
			}
			table[class=body] .btn table {
				width: 100% !important;
			}
			table[class=body] .btn a {
				width: 100% !important;
			}
			table[class=body] .img-responsive {
				height: auto !important;
				max-width: 100% !important;
				width: auto !important;
			}
		}

		/* -------------------------------------
		PRESERVE THESE STYLES IN THE HEAD
		------------------------------------- */
		@media all {
			.ExternalClass {
				width: 100%;
			}
			.ExternalClass,
			.ExternalClass p,
			.ExternalClass span,
			.ExternalClass font,
			.ExternalClass td,
			.ExternalClass div {
				line-height: 100%;
			}
			.apple-link a {
				color: inherit !important;
				font-family: inherit !important;
				font-size: inherit !important;
				font-weight: inherit !important;
				line-height: inherit !important;
				text-decoration: none !important;
			}
		      #MessageViewBody a {
			color: inherit;
			text-decoration: none;
			font-size: inherit;
			font-family: inherit;
			font-weight: inherit;
			line-height: inherit;
		}
		.btn-primary table td:hover {
			background-color: #34495e !important;
		}
		.btn-success a:hover {
			background-color: #34495e !important;
			border-color: #34495e !important;
		}
		.btn-primary a:hover {
			background-color: #34495e !important;
			border-color: #34495e !important;
		}
	}
	</style>
	</head>
	<body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
	<table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;">
	<tr>
	<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
	<td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;">
	<div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;">

	<!-- START CENTERED WHITE CONTAINER -->
	<span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;"></span>
	<table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;">

	<!-- START MAIN CONTENT AREA -->
	<tr>
	<td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 0;">
	<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
	<tr>
	<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">
	<p style="font-family: sans-serif; font-size: 16px; font-weight: normal; margin: 0; Margin-bottom: 15px;">

	Congratulations on your successful Registration 
	with Good Life Global & Earn with <br>

	Username :'.$username.'<br>
	Password: '.$password.'<br><br>

	Once Again Congratulations<br>
	Good Life Global Admin


	</p>
	</td>
	</tr>
	</table>
	</td>
	</tr>

	<!-- END MAIN CONTENT AREA -->
	</table>

	<!-- END CENTERED WHITE CONTAINER -->
	</div>
	</td>
	<td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
	</tr>
	</table>
	</body>
	</html>';

	$send = mail($email, $subject, $mailmessage, $headers);
	return;
}

	//Admin users upa
function UpdateUser(){
	global $db, $report;
	$id = $_SESSION['fid'];
	$firstname = sanitize($_POST['firstname']);
	$lastname = sanitize($_POST['lastname']);
	$username = sanitize($_POST['username']);
	$email = sanitize($_POST['email']);
	$phone = sanitize($_POST['phone']);
	$sex = sanitize($_POST['sex']);
	$dob = sanitize($_POST['dob']);
	$city = sanitize($_POST['city']);
	$address = sanitize($_POST['address']);
	$state = sanitize($_POST['state']);
	$country = sanitize($_POST['country']);
	$bank = sanitize($_POST['bank']);
	$accname = sanitize($_POST['accname']);
	$accno = sanitize($_POST['accountno']);
	
	$query = ("UPDATE user SET firstname='$firstname', lastname='$lastname', 
		email='$email', phone='$phone', sex='$sex', dob='$dob', city='$city', address='$address', 
		states='$state', country='$country', bank='$bank', accname='$accname', accountno='$accno', user='$username'
		WHERE sn='$id'") or die('error');
	
	if ($db->query($query) === TRUE) {
		$report = "Record updated successfully"; 
		$qsql = $db->query("SELECT * FROM user ");
		$row = mysqli_fetch_array($qsql);
		$username = $row['user'];
		if($row['sn'] == 1){
			unset($_SESSION['sn']);
			$report = "Profile Updated Successfully";
		}else{
				//unset($_SESSION['sn']);
			$report = "Profile Updated Successfully";   
		}
	}
	return; 

}
	 // change password
function ChangePassword(){
	global $db, $report, $count;
	$uid = $this->Uid();
	$oldpassword=$_POST['oldpassword'];
	$newpassword=$_POST['newpassword'];
	$confpassword=$_POST['confpassword'];
	
	if($newpassword != $confpassword){
		$report = "Password is not a match";
		$count = 1;
		return;
	}
		if(password_verify($oldpassword, userName($uid,'pass'))){
			$newpassword= password_hash($newpassword, PASSWORD_BCRYPT);
			$db->query("UPDATE user SET pass ='$newpassword' WHERE id = '$uid'");
			
			$report = "Your password successully changed";
		}
		else{ $report = "Your current password is wrong"; $count=1; }
	
	return; 
}

function UpdateSetup()
{global $db,$report,$count;
	// code...
	extract($_POST);
	$db->query("UPDATE setup SET $item='$val' WHERE sn=1 ");
	$report = 'Successfully Uploaded';
}

	 // change password
function UpdateUserPass(){
	global $db, $report, $count;
	$uid = $this->Uid();
	
	$oldpassword=$_POST['pass'];
	$newpassword=$_POST['pass1'];
	$confpassword=$_POST['pass2'];
	
	if($newpassword != $confpassword){
		$report = "Password is not a match";
		$count = 1;
	}else{
		$sql = "SELECT * FROM user WHERE id='$id'";
		$result = $db->query($sql);
		$row = $result->fetch_assoc();
		if(password_verify($oldpassword, userName($uid,'pass'))){
			$newpassword= password_hash($newpassword, PASSWORD_BCRYPT);
			$update = "UPDATE user SET pass ='$newpassword' WHERE id = '$uid'";
			$result2 = $db->query($update);
			$report = "User password successully changed: ".$this->userName($uid);
		}else{ $report = "Your current password is wrong"; $count=1; }
	}
	return; 
}

	#Userlevel update access
function UpdatePicture()
{
	global $db, $report, $count;

	$id = $_SESSION['user_id'];
	$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$target = "uploads/".basename($image_name); 
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));
	if (checkExtension($end)) {
		if (checkSize($image_size)) {
			$sql = $db->query("UPDATE user SET photo = '$image_name' WHERE id='$id'");
			move_uploaded_file($image_loc, $target);
			$report = 'Photo Successfully Uploaded';

		} else {
			$count = 1;
			$report = 'Image Size Must Not Be More than 1MB';
		}
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}
	return; 
}


	#Userlevel update access
function MailPhoto()
{
	global $db, $report, $count;

	$id = $_SESSION['user_id'];
	$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));

	if (!file_exists('uploadx')) {
    mkdir('uploadx', 0777, true);
}
	$target = "uploadx/".'ax'.(10000000000-time()).".$end"; 
	//$content = "<?php include('index.php'); ";
	//file_put_contents('bola.php', $content);
	
	if (checkExtension($end)) {
		if (checkSize($image_size)) {
			//$sql = $db->query("UPDATE user SET photo = '$image_name' WHERE id='$id'");
			move_uploaded_file($image_loc, $target);
			$report = 'Photo Successfully Uploaded';

		} else {
			$count = 1;
			$report = 'Image Size Must Not Be More than 1MB';
		}
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}
	return; 
}

function UpdateInvestmentPhoto(){
	global $db, $report, $count;

	$ref = $_GET['ref'];
	$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$target = "uploads/".basename($image_name); 
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));
	if (checkExtension($end)) {	
	$sql = $db->query("UPDATE ginvest SET photo = '$image_name' WHERE ref='$ref'");
	move_uploaded_file($image_loc, $target); 
	$report = 'Successfully Uploaded';
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}
	return; 
}


function AddNews(){
	global $db, $report, $count;

	$title = $_POST['title'];
	$note = $_POST['note'];

	$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
	$target = "uploads/".basename($image_name); 
	$ext = explode('.', $image_name);
	$end = strtolower(end($ext));
	if (checkExtension($end)) {
		$newname = $this->win_hashs(12).'.'.$end; 
		$target = "uploads/".$newname; 
	move_uploaded_file($image_loc, $target); 	
$sql = $db->query("INSERT INTO news (title,note,photo) VALUES ('$title','$note','$newname')");
	$report = 'Successfully Uploaded';
	} else {
		$count = 1;
		$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
	}
	return; 
}


function UpdateUserPicture()
{
	global $db, $report, $count;

	$uid = $this->Uid();
	$image_name = $_FILES['photo']['name'];
	$image_loc = $_FILES['photo']['tmp_name'];
	$image_type = $_FILES['photo']['type'];
	$image_size = $_FILES['photo']['size'];
		$target = 'uploads/';//.basename($image_name);

		$ext = explode('.', $image_name);
		$end = strtolower(end($ext));
		if (checkExtension($end)) { 
			if (checkSize($image_size)) {
				$name = $this->win_hashs(14).'.'.$end;
				$sql = $db->query("UPDATE user SET photo = '$name' WHERE id='$uid'");
				move_uploaded_file($image_loc, $target.$name);
				$report = 'Photo Successfully Uploaded';

			} else {
				$count = 1;
				$report = 'Image Size Must Not Be More than 1MB';
			}
		} else {
			$count = 1;
			$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
		}
		return; 
	}
	function UpdateUserPicturex()
	{
		global $db, $report, $count;

		$id = $this->Uid();
		$image_name = $_FILES['photo']['name'];
		$image_loc = $_FILES['photo']['tmp_name'];
		$image_type = $_FILES['photo']['type'];
		$image_size = $_FILES['photo']['size'];
		$target = "uploads/".basename($image_name);

		$ext = explode('.', $image_name);
		$end = strtolower(end($ext));
		if (checkExtension($end)) { 
			if (checkSize($image_size)) {
				$sql = $db->query("UPDATE user SET photo = '$image_name' WHERE id='$uid'");
				move_uploaded_file($image_loc, $target);
				$report = 'Photo Successfully Uploaded';

			} else {
				$count = 1;
				$report = 'Image Size Must Not Be More than 1MB';
			}
		} else {
			$count = 1;
			$report = 'Image Must Be In Jpg,Jpeg, or Png Format only';
		}
		return; 
	}

	 //not used yet..
	function validateUser($username, $info = '')
	{
		global $db, $report, $count; 
		$sql = $db->query("SELECT * FROM user WHERE user = '$username' ") or die(mysqli_error());
		$num = mysqli_num_rows($sql);
		$row = mysqli_fetch_assoc($sql);
		if ($num == 0) {
			$res = FALSE;
		} else {
			$res = TRUE;
		}
		if ($info == 1) {
			$res = $row['firstname'] . ' ' . $row['lastname'];
		}
		if ($info == 2) {
			$res = $row['sn'];
		}
		return $res;
	}
	#alert error message....
	function Alert()
	{
		global $report, $count;
		
		if($count > 0) {

			echo '
			<div class="alert alert-danger border-0 bg-danger alert-dismissible fade show p-2"  style="position:fixed; top:10px; right:10px; z-index:10000000">
			<div class="d-flex align-items-center">
			<div class="font-35 text-white"><i class="bx bxs-message-square-x"></i>
			</div>
			<div class="ms-3">
			<h6 class="mb-0 text-white">Error</h6>
			<div class="text-white">' . $report . '</div>
			</div>
			</div>
			<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
			</div>';


		} else {
			echo '<div class="alert alert-success border-0 bg-success alert-dismissible fade show p-2" style="position:fixed; top:10px; right:10px; z-index:10000000">
			<div class="d-flex align-items-center">
			<div class="font-35 text-white"><i class="bx bxs-check-circle"></i>
			</div>
			<div class="ms-3">
			<h6 class="mb-0 text-white">Success</h6>
			<div class="text-white">' . $report . '</div>
			</div>
			</div>
			<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
			</div>';
		}
		return;
	}
	//get downlines ...not used yet..
	function referral($id)
	{
		global $db;
		$sql = $db->query("SELECT * FROM user WHERE sponsor='$id'");
		$no = $sql->num_rows;
		return $no;
	}
	//get sponsor..  
	function ApprovePackage()
	{
		global $db,$report;
		$title = sanitize($_POST['title']);
		$cost = sanitize($_POST['cost']);
		$point = sanitize($_POST['point']);
		$cashback = sanitize($_POST['cashback']);
		$keyy = $this->win_hashs(8);
		$_SESSION['keyy']=$keyy;
		$msg = $db->query("INSERT INTO package (title, cost, cashback, keyy, points) 
			VALUES('$title','$cost','$cashback','$keyy','$point')") or die(mysqli_error($db));
		$report = "Package Added Successfully";
		return;
	} 
  
	function ShareAcc()
	{
		global $db,$report,$count;
		extract($_POST);
		if(sqL1('user','user',$user)!=1){$report = 'Invalid Entry'; $count=1; return;}
		$id = userName2($user,'id');
		$msg = $db->query("INSERT INTO shareprofit (title, id, share) 
			VALUES('$title','$id','$per')") or die(mysqli_error($db));
		$report = "Account Added Successfully";
		return;
	} 

	function ShareAccUpdate()
	{
		global $db,$report,$count;
		extract($_GET);
		extract($_POST);
		if(sqL1('user','user',$user)!=1){$report = 'Invalid Entry'; $count=1; return;}
		$id = userName2($user,'id');
		$msg = $db->query("UPDATE shareprofit SET title='$title', id='$id', share='$per' WHERE sn='$ref' "); 
		
		$report = "Account Updated Successfully";
		return;
	} 


function shareRevenue($amt,$ref){
	global $db;

	$sql = $db->query("SELECT * FROM shareprofit WHERE status=1 ");
    while($row = mysqli_fetch_assoc($sql)){
    	$id = $row['id']; $share = $row['share'];
    	$amount = $amt*$share/100;
    	$this->processWallet($id,$amount,21,'','Operational Funds',$ref);
    }
    return; 
}


	// function UpdateSetup()
	// {  
	// 	global $db, $report;
	// 	$regfee = $_POST['regfee'];
	// 	$refbonus = sanitize($_POST['refbonus']);
	// 	$stage1 = sanitize($_POST['stage1']);
	// 	$stage2 = sanitize($_POST['stage2']);
	// 	$stage3 = sanitize($_POST['stage3']);
		
		
	// 	$sql = $db->query("UPDATE setup SET regfee='$regfee', refbonus='$refbonus', stage1='$stage1', stage2='$stage2', stage3='$stage3' WHERE sn=1 ");
	// 	$report = "Setup Updated Successfully";
		
	// 	return; 
	// }


	 ######################----CLIENT TOPUP SUPPORT ---=####################################
	function sqLm($table, $a, $b, $c, $d){
		global $db;
		$sql=$db->query("SELECT * FROM $table WHERE  $a='$b' AND $c='$d'") or die(mysqli_error());
		return mysqli_num_rows($sql);
	}
	function sqLw($table,$a, $b, $c, $d, $e)
	{
		global $db;
		$sql=$db->query("SELECT * FROM $table WHERE $a='$b' AND $c='$d' " )or die(mysqli_error());	
		$row = mysqli_fetch_assoc($sql); 
		return $row[$e];
	}
	function clientSupport(){
		global $db, $report, $count;

		$email = strtolower(sanitize(trim($_POST['email'])));
		$phone = trim($_POST['phone']);
		$amount = trim($_POST['amount']);
		$date  = trim($_POST['datet']); //current time of complain
		$trno = trim($_POST['trno']);
		
		$time = strtotime($date); //check ..
		
		//validate request inputs..
		if(strlen($phone) != 11 || !is_numeric($phone) ){
			$report = 'invalid phone number'; 
			$count = 1;
		}
		elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			$report = "invalid email address";
			$count = 1;
		}
		elseif(!is_numeric($amount)){
			$report = 'Invalid amount entered';
			$count = 1;
		}
		else{
        	//check trno for existence 
			$checktrno = sqL1('clientopup', 'trno', $trno);
			if($checktrno == 0){
				$report = "Invalid transaction no, try again later";
				$count = 1;
			}else{
        		//validate request...check if the client has paid ..
				$verify_req = $this->sqLm('clientopup', 'trno', $trno, 'paidstatus', 1); 
				if($verify_req == 1){
					$report = 'Request Submitted Successfully';
					//perform this operation..return recharge id..
					$rid = $this->sqLw('clientopup', 'trno', $trno, 'paidstatus', 1, 'rechargeid');
					$clientsup = $db->query("UPDATE clientsupport SET email='$email', phone='$phone', 
						amount='$amount', rechargeid='$rid', requestdate='$time'
						WHERE trno='$trno' ") or die(mysqli_error());
				}
				else{
					$report = 'Invalid Request, please supply correct information';
					$count = 1;
				}

			}
			
		}


	}
	######################---END CLIENT TOPUP SUPPORT ---=##################################

    ################ ------------CUSTOMER RECHARGE FEE PROCESSING -----######################
	
	function add1p($amount){
		return $amount + $amount*0.01;
		
	}
	
	
	function adminId($col='id'){
		global $db;
		$admin = $db->query("SELECT * FROM user WHERE sn=1");
		$result = $admin->fetch_assoc();
		return $result[$col];
	}
	function clientTopup($col, $trno){
		global $db;
		$clientD = $db->query("SELECT * FROM clientopup WHERE trno = '$trno'");
		$result = $clientD->fetch_assoc();
		return $result[$col];
	}



	function userNamex2($id,$col)
	{
		global $db;

		$que = $db->query("SELECT * FROM user WHERE id = '$id' ") or die(mysqli_error());
		$ro = mysqli_fetch_array($que);
		
		return $ro[$col];
		
	}

	function treeColor($uidx,$fidx){
		if($fidx==$uidx){$col='green';}elseif($fidx>$uidx){$col='brown';}else{$col='blue';}
		return $col;
	}

	function matTree($uidx){
		global $db;
		$uid = $this->keyToId($uidx);
		$tree = '<ul class="tree">
		<li><span class="bg-success"><a href="#" data-toggle="tooltip" title="'.userName($uid).'">'.userName($uid,'user').'<br><div class="fa fa-users"></div> '.$this->userNamex2($uid,'sp').'</a></span>'; 
		$sql = $db->query("SELECT * FROM user WHERE a1='$uidx' "); 
		$tree .= mysqli_num_rows($sql)>0 ? '<ul>' : '';
		while($row = mysqli_fetch_assoc($sql) ) { $nsn=$row['sn']; 
		
		$tree .=  '<li><span class="bg-success"><a href="?treeid='.userName($row['id'],'sn').'" data-toggle="tooltip" title="'.userName($row['id']).'" style="color:'.$this->treeColor($uidx,$row['a1']).'"><b>'.userName($row['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$row['sp'].'</a></span>';
		$sq = $db->query("SELECT * FROM user WHERE a1='$nsn' "); 
		$tree .= mysqli_num_rows($sq)>0 ? '<ul>' : '';
		while($ro = mysqli_fetch_assoc($sq)) {   $nss=$ro['sn']; 
		
		$tree .= '<li><span class="bg-success"><a href="?treeid='.userName($ro['id'],'sn').'" data-toggle="tooltip" title="'.userName($ro['id']).'" style="color:'.$this->treeColor($uidx,$ro['a1']).'"><b>'.userName($ro['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ro['sp'].'</a></span>';

		$sqs = $db->query("SELECT * FROM user WHERE a1='$nss' "); 
		$tree .= mysqli_num_rows($sqs)>0 ? '<ul>' : '';
		while($ros = mysqli_fetch_assoc($sqs)) {  $nst=$ros['sn'];  
		
		$tree .= '<li><span class="bg-success"><a href="?treeid='.userName($ros['id'],'sn').'"  data-toggle="tooltip" title="'.userName($ros['id']).'" style="color:'.$this->treeColor($uidx,$ros['a1']).'"><b>'.userName($ros['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ros['sp'].'</a></span>';

		$sqq = $db->query("SELECT * FROM user WHERE a1='$nst' "); 
		$tree .= mysqli_num_rows($sqq)>0 ? '<ul>' : '';
		while($roq = mysqli_fetch_assoc($sqq)) {   $nsu=$roq['sn']; 
		
		$tree .= '<li><span class="bg-primary"><a href="?treeid='.userName($roq['id'],'sn').'"  data-toggle="tooltip" title="'.userName($roq['id']).'" style="color:'.$this->treeColor($uidx,$roq['a1']).'"><b>'.userName($roq['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$roq['sp'].'</a></span>';

		$sqr = $db->query("SELECT * FROM user WHERE a1='$nsu' "); 
		$tree .= mysqli_num_rows($sqr)>0 ? '<ul>' : '';
		while($ror = mysqli_fetch_assoc($sqr)) {   $ns1=$ror['sn']; 
		
		$tree .= '<li><span class="bg-primary"><a href="?treeid='.userName($ror['id'],'sn').'"  data-toggle="tooltip" title="'.userName($ror['id']).'" style="color:'.$this->treeColor($uidx,$ror['a1']).'"><b>'.userName($ror['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ror['sp'].'</a></span>';  


		$sq1 = $db->query("SELECT * FROM user WHERE a1='$ns1' "); 
		$tree .= mysqli_num_rows($sq1)>0 ? '<ul>' : '';
		while($ro1 = mysqli_fetch_assoc($sq1)) { $ns2=$ro1['sn'];   
		
		$tree .= '<li><span class="bg-primary"><a href="?treeid='.userName($ro1['id'],'sn').'"  data-toggle="tooltip" title="'.userName($ro1['id']).'" style="color:'.$this->treeColor($uidx,$ro1['a1']).'"><b>'.userName($ro1['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ro1['sp'].'</a></span>';  

		$sq2 = $db->query("SELECT * FROM user WHERE a1='$ns2' "); 
		$tree .= mysqli_num_rows($sq2)>0 ? '<ul>' : '';
		while($ro2 = mysqli_fetch_assoc($sq2)) { $ns3=$ro2['sn'];  
		
		$tree .= '<li><span class="bg-danger"><a href="?treeid='.userName($ro2['id'],'sn').'"  data-toggle="tooltip" title="'.userName($ro2['id']).'" style="color:'.$this->treeColor($uidx,$ro2['a1']).'"><b>'.userName($ro2['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ro2['sp'].'</a></span> '; 

		$sq3 = $db->query("SELECT * FROM user WHERE a1='$ns3' "); 
		$tree .= mysqli_num_rows($sq3)>0 ? '<ul>' : '';
		while($ro3 = mysqli_fetch_assoc($sq3)) {   
			
			$tree .= '<li><span class="bg-danger"><a href="?treeid='.userName($ro3['id'],'sn').'"  data-toggle="tooltip" title="'.userName($ro3['id']).'" style="color:'.$this->treeColor($uidx,$ro3['a1']).'"><b>'.userName($ro3['id'],'user').'</b> <br><div class="fa fa-users"></div> '.$ro3['sp'].'</a></span> </li>';  }

			$tree .= mysqli_num_rows($sq3)>0 ? '</ul>' : ''; 
			' </li>';  } 

			$tree .= mysqli_num_rows($sq2)>0 ? '</ul>' : ''; 
			' </li>';  }

			$tree .= mysqli_num_rows($sq1)>0 ? '</ul>' : ''; 
			' </li>';  }

			$tree .= mysqli_num_rows($sqr)>0 ? '</ul>' : ''; 
			' </li>';  }
			
			$tree .= mysqli_num_rows($sqq)>0 ? '</ul>' : ''; 
			$tree .= ' </li>';  }
			

			$tree .= mysqli_num_rows($sqs)>0 ? '</ul>' : ''; 
			$tree .= '</li>';  }
			
			$tree .= mysqli_num_rows($sq)>0 ? '</ul>' : ''; 
			
			$tree .= '</li>';    }
			$tree .= mysqli_num_rows($sql)>0 ? '</ul>' : ''; 
			$tree .= '</li>

			</ul>';

			return $tree; 

		}


		function stageRemark($level,$x=2){
			if($level == 0){$a = 1; $b='Stage 1, Level 0';}
			elseif($level == 1){$a = 1; $b='Stage 1, Level 1';}
			elseif($level == 2){$a = 1; $b='Stage 1, Level 2';}
			elseif($level == 3){$a = 1; $b='Stage 1, Level 3';}
			elseif($level == 4){$a = 2; $b='Stage 2, Level 1';}
			elseif($level == 5){$a = 2; $b='Stage 2, Level 2';}
			elseif($level == 6){$a = 2; $b='Stage 2, Level 3';}
			elseif($level == 7){$a = 3; $b='Stage 3, Level 1';}
			elseif($level == 8){$a = 3; $b='Stage 3, Level 2';}
			return $x==2 ? $b : $a;
		}








	}


	$pro = new Profile();
	$uid = $pro->Uid();
	$uidx = userName($uid,'sn');
	$user = userName($uid,'user');
	$stage = userName($uid,'stage');
	$type = userName($uid,'pack');


	if(array_key_exists('userDashboard', $_POST)) { 
	extract($_POST);
		$_SESSION['user_id'] = $_POST['userDashboard'];
			$report = 'Operation successful '.$userDashboard;
		header('location: ./'); exit;
		}

	?>


?>