Your IP : 3.17.175.191


Current Path : /home/lentoinv/covisclubinternational.com/profile/lib/achive/
Upload File :
Current File : //home/lentoinv/covisclubinternational.com/profile/lib/achive/class3003.php

<?php



class Signup{
			
    /* Class constructor */
   function __construct(){
	
	   if(array_key_exists('findSponsor', $_POST)){ $this->findSponsor(); }
	   if(array_key_exists('changeSponsor', $_POST)){ $_SESSION['signup']=NULL; }
	    if(array_key_exists('changeLogin', $_POST)){ $_SESSION['signup']=2; }
	    if(array_key_exists('regContinue', $_POST)){ $_SESSION['signup']=5; 
	    $head = $this->win_hash(85); header("location: ?user_ref=$head"); }
	    if(array_key_exists('searchU', $_POST)){ $this->searchU(); }
	    if(array_key_exists('signupUser', $_POST)){ $this->signupUser(); }
	   if(array_key_exists('payWithPin', $_POST)){ $this->payWithPin(); }
	   if(array_key_exists('resetPass', $_POST)){ $this->resetPass(); }
	   if(array_key_exists('updateSignup', $_POST)){ $this->updateSignup(); }
	   if(array_key_exists('resetPassConfirm', $_POST)){ $this->resetPassConfirm(); }
	   if(array_key_exists('signupUserIni', $_POST)){ $this->signupUserIni(); }
	   if(isset($_GET['tr_reference'])){ $this->confirmPayment();}
	    
	    if(isset($_GET['ref'])){ $this->refLink(); }
	     if(isset($_GET['reff'])){ $this->findSponsorx(); }
	    if(isset($_GET['form'])){ if($_GET['form']=='reset'){session_destroy(); header('location: signup.php');} }
	  return;
	  }
	 

	 function refLink(){
$this->findSponsor();
	return;
}

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

 $user = isset($_POST['sponsor']) ? strtolower(sanitize($_POST['sponsor'])) : strtolower($_GET['ref']);
     if($this->validateUser($user)==FALSE OR $this->pinMultiplex($user)>1){ $report = 'You have entered an invalid sponsor ID. Please Try Again'; $count=1; 
        } else{
            $_SESSION['signup']=2;
            $_SESSION['sponsorUsername'] = $user; 
           
        $_SESSION['sponsor'] = $this->validateUser($user,1); 
          $_SESSION['sponsorId'] = $this->validateUser($user,2); 
                 $report = 'Sponsor Successfully Validated';
                 if(isset($_GET['ref'])){ header('location: ?'); }
 }

return;
	}

function pinMultiplex($username){
		global $db;
	$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error());
	$row = mysqli_fetch_assoc($sql); $pin = $row['pin'];
	$sq=$db->query("SELECT * FROM user WHERE pin = '$pin' " )or die(mysqli_error());

return mysqli_num_rows($sq);
	}

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

 $user = strtolower($_GET['reff']);
     if($this->validateUser($user)==FALSE){ $report = 'You have entered an invalid sponsor ID. Please Try Again'; $count=1; 
        } else{
            $_SESSION['signup']=2;
            $_SESSION['sponsorUsername'] = $user; 
            $_SESSION['reff'] = $user; 
           
        $_SESSION['sponsor'] = $this->validateUser($user,1); 
          $_SESSION['sponsorId'] = $this->validateUser($user,2); 
                 $report = 'Sponsor Successfully Validated';

                 header('location: ?');
                 //$count=''; 
                
 }

return;
	}




function confirmPayment(){
	global $db;
	$payref = $_GET['tr_reference'];
	

	if($_GET['tr_reference']==$_SESSION['referenc']){
		$this->signupUser(); 
		$_SESSION['signup']=4;
	}
	unset($_SESSION['referenc']);
	header("location: ?payment-confirmed#online");
	return;
}


function wildSponsored($key){
			global $db,$user;
			$qu=$db->query("select * FROM user WHERE sponsor = '$key' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			return $nu;	
			}




	function validateUser($username,$info=''){
		global $db,$report,$count;
//$sql=$db->query("SELECT * FROM user WHERE user = '$username' OR email = '$username' " )or die(mysqli_error()); 
$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;
	}



		function searchU(){
		global $db,$report,$count;
$username = sanitize($_POST['u-ref']);
$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error()); 
$row=mysqli_fetch_assoc($sql);
$uref = sha1($row['sn']);
header("location: searchuser.php?u-ref=$uref");
return;
	}




function signupUserIni(){
	global $report, $count;
	$report='';
	
   /*  $_SESSION['firstname'] = ucwords(strtolower($this->valEmpty($_POST['firstname'],'Firstname')));
     $_SESSION['lastname'] = ucwords(strtolower($this->valEmpty($_POST['lastname'],'Lastname')));
     $_SESSION['address'] = addslashes(ucwords(strtolower($this->valEmpty($_POST['address'],'Address'))));
     $_SESSION['state'] = $this->valEmpty($_POST['state'],'State');
     $_SESSION['city'] = ucwords($this->valEmpty($_POST['city'],'City'));
     $_SESSION['phone'] = $this->valPhone($_POST['phone']);
     */
$_SESSION['email'] = strtolower($this->valEmpty(sanitize($_POST['email']),'E-mail'));

$_SESSION['username'] = strtolower($this->valEmpty(sanitize($_POST['username']),'Username'));
$_SESSION['pwd'] = md5($this->valPass($_POST['passw']));
$_SESSION['pwd2'] = md5($_POST['passw2']);
$_SESSION['password'] = $_POST['passw'];
if($_SESSION['pwd'] != $_SESSION['pwd2']){$report .= "<br>Password confirmation failed, Try again"; $count = 1; }
if($this->userExist($_SESSION['username'],$_SESSION['email'])==TRUE){
$report .= "<br>A user with this username already exist. Try again."; 
 $count = 1;}

if(!empty($count)){ }else{
$report = "<br>Login Information successfully submitted"; 
$_SESSION['signup']=3;
//if(isset($_GET['ref'])){ header('location: ?'); }
}


return;
}


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 valPhone($field){
	global $report, $count;
	$field = sanitize(trim($field));
if($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 valPass($field){
	global $report, $count;
if($field==''){$report .= "<br>Password field is required! "; $count=1; return;}elseif(strlen($field)<6){$report .= "<br>Password cannot be less than 6 characters! "; $count=1; return;}else{
return sanitize($field); }
}


function pinValidity($pin){
	global $db,$report,$count;
	$sql=$db->query("SELECT * FROM pin WHERE pin = '$pin' " )or die(mysqli_error()); 
$row = mysqli_fetch_assoc($sql);
$num=mysqli_num_rows($sql);
if($num==0){$report = 'You have entered an invalid E-PIN, verify your E-PIN and try again';  $count=1; $valid=FALSE; }
elseif($num==1 AND $row['status']==0){$valid=TRUE;}
else{$valid=FALSE; $report = 'This E-PIN has already been used by: '.$this->userName2($row['id']).' as at '.$row['created']; $count=1; }
return $valid;
}


function payWithPin(){
global $db,$count,$report,$username,$pin;
$pin = strtoupper(sanitize($_POST['epin']));
$sql=$db->query("select * FROM pin WHERE pin = '$pin' " )or die(mysqli_error()); 
$row = mysqli_fetch_assoc($sql);
$num=mysqli_num_rows($sql);
if($num==1){
if($row['status']==1){$report = 'This E-PIN has already been used by: '.$this->userName2($row['id']).' as at '.$row['created']; $count=1; }elseif($row['status']==0){ 
$this->signupUser(); 
$sql=$db->query("UPDATE pin SET status = 1, id = '$username' WHERE pin = '$pin' " )or die(mysqli_error());  }

	}else{

		$report = 'You have entered an invalid E-PIN, verify your E-PIN and try again';  $count=1;
	
}

return;
}


/*

function payWithCoin(){
global $db,$username;
$pin = $_POST['pin'];
$sql=$db->query("SELECT * FROM pin ORDER BY sn ASC LIMIT 1 " )or die(mysqli_error()); 
$row = mysqli_fetch_assoc($sql);
$pin = $row['pin'];

	$this->signupUser(); 
	$sql=$db->query("UPDATE pin SET status = 1, id = '$username' WHERE pin = '$pin' " )or die(mysqli_error()); 
return;
}
*/


	 function signupUser(){
	 global $report, $count, $pwd, $pwd2, $username, $email;
	 
	 /*$firstname = $_SESSION['firstname'];
	 $lastname = $_SESSION['lastname'];
	 $address = $_SESSION['address'];
	 $state = $_SESSION['state'];
	 $city = $_SESSION['city'];
$phone = $_SESSION['phone'];
*/
$email = $_SESSION['email'];

$username = $_SESSION['username'];
$pwd = $_SESSION['pwd'];
$pwd2 = $_SESSION['pwd2'];

$sponsor = $_SESSION['sponsorId']; 

if($this->userExist($username,$email)==TRUE){
$report="A user with this username already exist. Try another Username. If you have registered before, go to login area and do password recovery ";	
 $count = 1;}elseif($pwd != $pwd2){$report="Password confirmation failed, Try again"; $count = 1; }else{

if($this->findUser($sponsor)==TRUE){	


			if($this->Downline($sponsor)<MATRIX){	
			$user = $sponsor;
			$this->Register($sponsor,$user);

						$report="You have been successfully registered directly under ".$this->userName($user);


				}        
			else{	
						$ge = 1;
					$user = $this->nextUpline($ge);
					$this->Register($sponsor,$user);
			
				$report="You have been successfully registered directly under ".$this->userName($user);
	
				}

         }else{
			 
			 $report="Sponsor Does not Exist"; $count = 1;
		      }
			  
}

return;
   }
	
	
	
	
			function userName($user){
				global $db;
			$que=$db->query("select * FROM user WHERE sn = '$user' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);	
				return $ro['firstname'].' '.$ro['lastname'];
			}	

			function userName2($user){
				global $db;
			$que=$db->query("select * FROM user WHERE user = '$user' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);	
				return $ro['firstname'].' '.$ro['lastname'];
			}	

function userName3($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 findUser($user){
		global $db;
		$sql=$db->query("select * FROM user WHERE sn = '$user' " )or die(mysqli_error()); 
$num=mysqli_num_rows($sql);
if($num==0){$res = FALSE; }else{$res = TRUE; }
return $res;
	}
	
	function userExist($username,$email){
		global $db,$report,$count;
//$sql=$db->query("SELECT * FROM user WHERE user = '$username' OR email = '$email' " )or die(mysqli_error()); 
	$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 Downline($user){
		global $db;
		$sql=$db->query("select * FROM user WHERE a1 = '$user' " )or die(mysqli_error()); 
$num=mysqli_num_rows($sql);
return $num;
	}
	
	
	
		function Register($sponsor,$user){
		global $db,$report,$count, $pwd, $username, $email, $pin;
		


$que=$db->query("select * FROM user WHERE sn = '$user' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);
					$a1 = $ro['sn'];
					$a2 = $ro['a1'];
					$a3 = $ro['a2'];
					$a4 = $ro['a3'];
					$a5 = $ro['a4'];
					$a6 = $ro['a5'];
					$a7 = $ro['a6'];
					$a8 = $ro['a7'];
					$a9 = $ro['a8'];
					$a10 = $ro['a9'];
					$a11 = $ro['a10'];
					$a12 = $ro['a11'];
					$a13 = $ro['a12'];
					$a14 = $ro['a13'];
					$a15 = $ro['a14'];
					$a16 = $ro['a15'];
					$a17 = $ro['a16'];
					$a18 = $ro['a17'];
					$a19 = $ro['a18'];
					$a20 = $ro['a19'];
					
					$id = $this->win_hashs(9);

				$reg = $db->query("INSERT INTO user (id,sponsor,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17,a18,a19,a20,email,user,pass,pin)
VALUES('$id','$sponsor','$a1','$a2','$a3','$a4','$a5','$a6','$a7','$a8','$a9','$a10','$a11','$a12','$a13','$a14','$a15','$a16','$a17','$a18','$a19','$a20','$email','$username','$pwd','$pin')") or die('Cannot Connect to Server');

$down=$db->query("SELECT * FROM user WHERE a1 = '$user' " )or die(mysqli_error());
$nd=mysqli_num_rows($down);

$upd = $db->query("UPDATE user SET active='$nd' WHERE sn = '$user' ");
$sp = $this->wildSponsored($sponsor);
$updx = $db->query("UPDATE user SET sp='$sp' WHERE sn = '$sponsor' ");
$_SESSION['signup']=4;

$subject = 'Registration Successful';
$msg = 'Thank you for signing up with Smile We-care! Welcome to the home of future business generals';
$this->message($id,$msg,$subject);

	$this->emailer($email);

return;
	}


function message($id,$msg,$subject){
global $db;
$ctime = CTIME;
$msg = $db->query("INSERT INTO msg (rec,subject,msg,ctime)
VALUES('$id','$subject','$msg','$ctime')") or die(mysqli_error());

	return;
}

function nextUpline($ge){
	global $db;
$sponsor = $_SESSION['sponsorId']; 
	 $gen = 'a'.$ge; 
	 
	 $matrix = MATRIX;
				$que=$db->query("SELECT * FROM user WHERE $gen = '$sponsor' AND active < '$matrix' ORDER BY sn ASC LIMIT 1" )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);
					$find = mysqli_num_rows($que);
					 $user = $ro['sn'];
					 if($find < 1){ $ge = $ge+1; $user = $this->nextUpline2($ge); }
					return $user;
					}
					
function nextUpline2($ge){
	global $db;
	$sponsor = $_SESSION['sponsorId']; 
	 $gen = 'a'.$ge; 
	 $matrix = MATRIX;
	 
				$que=$db->query("select * FROM user WHERE $gen = '$sponsor' AND active < '$matrix' ORDER BY sn ASC LIMIT 1" )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);
					$find = mysqli_num_rows($que);
					 $user = $ro['sn'];
					 if($find < 1){ $ge = $ge+1; $user = $this->nextUpline($ge); }
					return $user;
					}	
			

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

function resetPass(){
	global $db,$report,$count;
	$email = strtolower(trim(sanitize($_POST['emailreset'])));
$sql=$db->query("SELECT * FROM user WHERE email = '$email' " )or die('Could not initiate password reset');
$row=mysqli_fetch_array($sql);
$reset_order = $this->win_hash(41);
$find = mysqli_num_rows($sql);
if($find==0){$report='This email does not exist in our system, check and try again'; $count=1;}
elseif($find==1){
	$sql=$db->query("UPDATE user SET code='$reset_order' WHERE email = '$email' " )or die('Could not initiate password reset');
$message = 'You have requested for a password reset. Follow the link below to reset your password:<br>';
$message .= 'https://www.smilewecarengo.com/accountreset.php?request-index='.$reset_order;
$subject='Smile We-care Password Recovery';
$this->emailerAll($email,$message,$subject);
	$report='We have sent you an e-mail containing your password reset link. Follow the link to reset your password';
}

return;
}



function updateSignup(){
	global $db,$report,$count;
	$username = $_SESSION['username']; 
$firstname=ucwords(strtolower($this->valEmpty($_POST['firstname'],'Surname')));
$lastname=ucwords(strtolower($this->valEmpty($_POST['lastname'],'Other Names')));

$country=$_POST['country'];
$state=$_POST['state'];
$city=ucwords(strtolower($this->valEmpty($_POST['city'],'City')));
$address=addslashes(ucwords(strtolower($this->valEmpty($_POST['address'],'Address'))));
$phone=$this->valPhone($_POST['phone']);
$bank=ucwords(strtolower($this->valEmpty($_POST['bank'],'Bank')));
$accountno=$this->valEmpty($_POST['accountno'],'Account Number');
$course = $_POST['course'];

$dob=$this->valEmpty($_POST['dob'],'Date of Birth');
$sex=$_POST['sex'];
$accname=ucwords(strtolower($this->valEmpty($_POST['accname'],'Account Name')));
//$officeaddress=addslashes(ucwords(strtolower($_POST['officeaddress'])));

	  $photo = isset($_FILES['image']) ? str_replace(' ', '-', $username).$_FILES['image']['name'] : 'user.png';
	 if(isset($_SESSION['user_id'])){ define('upload', 'photo/'); }
	 else{ define('upload', 'dashboard/photo/'); }
	 $success = move_uploaded_file($_FILES['image']['tmp_name'], upload.$photo);
	



$db->query("UPDATE user SET country='$country', state='$state', city='$city', phone='$phone', address='$address', bank='$bank', accountno='$accountno', firstname='$firstname', lastname='$lastname', sex='$sex', dob='$dob', accname='$accname', photo='$photo' WHERE user = '$username' "); 
$id = $this->userName3($username);
$this->courseOrder2($id,$course); //submit required course
$report = 'User Registration Information Successfully Updated!'; $count=0;
$_SESSION['signup']=6;

	return;
}



function courseOrder2($userkey,$course){
		global $db;		
		
$tno = substr(str_shuffle(str_repeat('1234567890',10)),0,10);
$sql = $db->query("INSERT INTO download (id,course,tno) VALUES ('$userkey','$course','$tno')");

return;
}





function resetPassOrder(){
global $db;
$order = isset($_GET['request-index']) ? $_GET['request-index']:'';
$sql=$db->query("SELECT * FROM user WHERE code = '$order' " );
$find = mysqli_num_rows($sql);
if($find==1){return TRUE;}else{return FALSE;}
}


function resetPassConfirm(){
	global $db,$report,$count,$reset;
	$pwd1 = md5($_POST['password']);
	$pwd2 = md5($_POST['password2']);
	$reset_order = $this->win_hash(41);
	$code = $this->resetPassOrder() ? $_GET['request-index'] : 0;
if($pwd1==$pwd2){
$db->query("UPDATE user SET pass='$pwd1', code='$reset_order' WHERE code = '$code' "); $report = 'User Password Successfully Changed! You can now login to your account';
//header('location: ./login.php'); 
$reset=2;
}else{$report='New Password Mismatch, Try Again'; $count = 1;}


	  return;
}


function Alert(){
	global $report,$count;
	if($count>0){

			 echo '<div class="alert alert-danger alert-dismissible" style="position:fixed; top:10px; right:10px; z-index:10000">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <i class="icon fa fa-ban"></i>   &nbsp;&nbsp;'. $report .' &nbsp;&nbsp;&nbsp;
              </div>';	


	}
	else{
	 echo '<div class="alert alert-success alert-dismissible" style="position:fixed; top:10px; right:10px; z-index:10000">
                <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                <i class="icon fa fa-check"></i>  &nbsp;&nbsp;'. $report .'&nbsp;&nbsp;&nbsp;&nbsp;
              </div>';	
	}
//if(isset($report)){	unset($_SESSION['report']);  }
	return;
}






function emailerAll($email,$message,$subject){
	global $firstname;
$headers = 'From: SMILE WE-CARE <info@smilewecarengo.com>' . "\r\n";
$headers .= 'Reply-To: info@smilewecarengo.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 emailer($email){
	global $username;
$headers = 'From: SMILE WE-CARE <info@smilewecarengo.com>' . "\r\n";
$headers .= 'Reply-To: info@smilewecarengo.com' . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";


$subject = 'WELCOME TO SMILE WE-CARE';
$mailmessage = "<p>Welcome ".ucwords($username).'<br>Congratulation! You have successfully signed up with SMILE WE-CARE.  <br>Smile We-Care International (SWCI) is a Human Capacity Oriented Empowerment Based membership Multilevel Marketing (MLM) program duly registered with Corporate Affairs Commission, with great passion and dedicated to building a community of developed, Skilled and Financially free youths, Businessmen/Women in the society.</p>
<p>
We Impact lives through the provision of a wide-range of Humanitarian Services, Free Skill Acquisition, Multiple Streams of Income, Educational/Business fund support, Food Provision, Monthly leadership earnings, Human Capacity Development, at different stages in the programme. Welcome to the Smile We-care World. </p>
<p> Your login details include: <br> Username: '.$_SESSION['username'].'<br>Password: '.$_SESSION['password'].'<br>
click the button below to login to your account using your username and password<br><br>
<a href="https://smilewecarengo.com/login.php" style="border: thin solid #036; text-decoration:none; padding:10px 25px; margin:10px;"> Account Login</a><br><br><br> We hope to have a fruitful business relationship with you.</p>';


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


			
		}
		
$signup = new Signup;
		//End of abc class


		
		
		


















	
	//User Profile Class

		if(isset($_SESSION['user_id'])){	
$userKey = $_SESSION['user_id'];
}	

	
class Profile{
	var $amount = 2500;  //Registration Fee
	var $dola = 250;  // Dollar conversion to Naira
	var $dolafee = 10; //Registration fee in dolla
	var $minwithdraw = 10;
	var $maxwithdraw = 2000;
	var $withdrawcharge = 0;//0.5;
	//var $regfee = 10;
		


private function layerKey(){
return $_SESSION['user_id'];
}
	
	
	//User Array Keys 
	/* Class constructor */
	   function __construct(){
	   	global $report,$count;
	 	if(array_key_exists('changePassword', $_POST)){ $this->changePassword(); }
	 	if(array_key_exists('changePassword2', $_POST)){ $this->changePassword2(); }
	  	if(array_key_exists('UpdateUser', $_POST)){ $this->UpdateUser(); }
	  	if(array_key_exists('UpdateUser2', $_POST)){ $this->UpdateUser2(); }
	   	if(array_key_exists('updatePhoto', $_POST)){ $this->updatePhoto(); }
	   	if(array_key_exists('updatePhoto2', $_POST)){ $this->updatePhoto2(); }
	   	if(array_key_exists('LoginUsers', $_POST)){ $this->LoginUsers(); }
	    if(array_key_exists('withdrawOrder', $_POST)){ $this->withdrawOrder(); }
	    if(array_key_exists('transferOrder', $_POST)){ $this->transferOrder(); }
	    if(array_key_exists('courseOrder', $_POST)){ $this->courseOrder(); }
	    if(array_key_exists('buyEpins', $_POST)){ $this->buyEpins(); }
	    if(array_key_exists('sendMessage', $_POST)){ $this->sendMessage(); }
	    if(array_key_exists('sendMessageToAll', $_POST)){ $this->sendMessageToAll(); }
	    if(array_key_exists('createPin', $_POST)){ $this->createPin(); }
	    if(array_key_exists('stg', $_POST)){ $_SESSION['stg']=$_POST['stg']; }
	    if(array_key_exists('resetChart', $_POST)){ $this->resetChart(); }
	       if(array_key_exists('showAwardee', $_POST)){ $this->showAwardee(); }
	       if(array_key_exists('approveAward', $_POST)){ $this->approveAward(); }
	       if(array_key_exists('approveWithdrawOrder', $_POST)){ $this->approveWithdrawOrder(); }
	       if(array_key_exists('approveIncentiveOrder', $_POST)){ $this->approveIncentiveOrder(); }
	       if(array_key_exists('SearchDownline', $_POST)){ $this->SearchDownline(); }
	       if(array_key_exists('SendUserMessage', $_POST)){ $this->SendUserMessage(); }
	       if(array_key_exists('DeactivateUser', $_POST)){ $this->DeactivateUser(); }
	        if(array_key_exists('UpdatePin', $_POST)){ $this->UpdatePin(); }
	       if(array_key_exists('CourseUpload', $_POST)){ $this->CourseUpload(); }
	       if(array_key_exists('processPin', $_POST)){ $_SESSION['processPin']=$_POST['processPin']; }
	       
	       if(array_key_exists('replyMsg', $_POST)){ $this->replyMsg(); }
	       if(array_key_exists('verifyUser', $_POST)){ $this->verifyUser(); }
	       if(array_key_exists('updateAward', $_POST)){ $this->updateAward(); }
	       if(array_key_exists('requestEpins', $_POST)){ $this->requestEpins(); }
	       if(array_key_exists('approvePinRequest', $_POST)){ $this->approvePinRequest(); }
	       if(array_key_exists('deletePinRequest', $_POST)){ $this->deletePinRequest(); }
	       if(array_key_exists('requestIncentive', $_POST)){ $this->requestIncentive(); }
	       if(array_key_exists('RestorePin', $_POST)){ $this->RestorePin(); }
	       if(isset($_GET['tr_referenca'])){ $this->confirmPinPayment();}

	       if(isset($_GET['payment-confirmed']) AND isset($_SESSION['report'])){$report = $_SESSION['report'];  }
	       if(isset($_GET['action'])){if($_GET['action'] =='logout'){ session_destroy(); header('location: ../'); exit; }}
	 return;
	  }
	  

function replyMsg(){
	global $db,$report,$count;
	$mid = $_GET['reply'];
	$reply = addslashes($_POST['replyMsg']);
if(strlen($reply)>5){
$msg = $db->query("INSERT INTO replymsg (mid,reply) VALUES('$mid','$reply')") or die(mysqli_error());
	$report = 'Reply sent successfully';
	} else{
		$report = 'Message too short'; $count = 1;
	}
	return;
}


function verifyUser(){
	global $db,$report,$count;
	$username = $_POST['user'];

$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error()); 
if(mysqli_num_rows($sql) > 0){
$row=mysqli_fetch_assoc($sql);
$_SESSION['recKey']=$row['id'];
$report = 'Beneficiary successfully verified';	
}
else{
		$report = 'Invalid Beneficiary, try again'; $count = 1;
	}
	return;
}


function SendUserMessage(){
	global $report;
	$rec = $_POST['SendUserMessage'];

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

$this->message($rec,'Admin',$message,$subject);
$report='Your message was successfully sent';
return;
}

function SearchDownline(){
		global $db,$report,$count;
$randomKey = $this->userName('sn');
$username = $_POST['u-ref'];

	
			$a = 1;  $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' AND user = '$username' " )or die(mysqli_error());
			$nu += mysqli_num_rows($qu);
			}

if($nu>0){
$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error()); 
$row=mysqli_fetch_assoc($sql);
$uref = sha1($row['sn']);
header("location: generations.php?u-ref=$uref");
}
else{$report ='Error! search could find the user in your team. confirm and try again'; $count=1; }
return;
	}


//*
function LoginUsers(){
	global $db,$report,$count;
	$username = strtolower(sanitize($_POST['usern']));
	$password = md5($_POST['passwo']);
	$sql = $db->query("SELECT * FROM user WHERE user='$username' ");
	$num = mysqli_num_rows($sql);

	if($num==1){
		$row = mysqli_fetch_array($sql);
		$pass = $row['pass'];
		$status = $row['status'];

		if($pass==$password){
			if($status==1 AND $this->pinMultiple($username)<=1){ 
		$_SESSION['signup'] = '';
		$_SESSION['user_id'] = $row['id']; 
		if(is_null($row['firstname']) OR is_null($row['lastname'])){$_SESSION['signup']=5; $_SESSION['username']=$username; header('location:signup.php');}else{
		header('location:dashboard/'); }
			}else{$report='Your user account has been deactivated, contact the system administrator '.$this->pinMultiple($username); $count=1;}
	}else{$report='Invalid Login details, Try again'; $count=1;}
	}else{$report='Invalid Login details, Try again'; $count=1;}
  return;
}
/*/


//*

function LoginUsers(){
	global $db,$report,$count;
	$username = strtolower(sanitize($_POST['usern']));
	$password = md5($_POST['passwo']);
	$sql = $db->query("SELECT * FROM user WHERE user='$username' ");
	$num = mysqli_num_rows($sql);

	        // access
        $secretKey = '6LfX8YkUAAAAANB4vBbm0dK-44AxhW6tkliSZTUl';
        $captcha = $_POST['g-recaptcha-response'];

        if(!$captcha){
          $report = 'Please check the the captcha form.';     $count=1;
        }
$ip = $_SERVER['REMOTE_ADDR'];
        $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
        $responseKeys = json_decode($response,true);

        if(intval($responseKeys["success"]) !== 1) {
          $report = 'Please check the the captcha form.';    $count=1;
        } else {

	if($num==1){
		$row = mysqli_fetch_array($sql);
		$pass = $row['pass'];
		$status = $row['status'];

		if($pass==$password){
			if($status==1 AND $this->pinMultiple($username)<=1){ 
		$_SESSION['signup'] = '';
		$_SESSION['user_id'] = $row['id']; 
		if(is_null($row['firstname']) OR is_null($row['lastname'])){$_SESSION['signup']=5; $_SESSION['username']=$username; header('location:signup.php');}else{
		header('location:dashboard/'); }
			}else{$report='Your user account has been deactivated, contact the system administrator'; $count=1;} 
	}else{$report='Invalid Login details, Try again'; $count=1;}
	}else{$report='Invalid Login details, Try again'; $count=1;}
 }
  return;
}
//*/


function validLayer(){
if(strlen($this->layerKey()) != 32){
		unset($_SESSION['user_id']);
	}else{}
	return;
}








function updateUser(){
	global $db,$report,$userKey;
$state=sanitize($_POST['state']);
$city=sanitize($_POST['city']);
$address=addslashes(sanitize($_POST['address']));
$phone=sanitize($_POST['phone']);
$bank=sanitize($_POST['bank']);
$accountno=sanitize($_POST['accountno']);


$db->query("UPDATE user SET state='$state', city='$city', phone='$phone', address='$address', bank='$bank', accountno='$accountno' WHERE id = '$userKey' "); 
$report = 'User Information Successfully Updated!';

	return;
}



function RestorePin(){
	global $db,$report;
$pin=$_POST['RestorePin'];

$db->query("UPDATE pin SET status=0, id='' WHERE pin = '$pin' "); 
$report = 'PIN Successfully Restored!';

	return;
}


function DeactivateUser(){
	global $db,$report;
$userKey=$_POST['DeactivateUser'];
$status = ($this->uName($userKey,'status')==1)?0:1;
$act = ($status==0)?'Deactivated!':'Activated!';

$db->query("UPDATE user SET status='$status' WHERE id = '$userKey' "); 
$report = $this->uName($userKey).' has been successfully '.$act;

	return;
}

function UpdatePin(){
	global $db,$report,$count,$signup;
$userKey=$_POST['UpdatePin'];
$pin=$_POST['pin'];
$user = $this->uName($userKey);
if($signup->pinValidity($pin)==TRUE){
$db->query("UPDATE user SET pin='$pin' WHERE id = '$userKey' "); 
$db->query("UPDATE pin SET status=1, id='$user' WHERE pin = '$pin' "); 
$report = $this->uName($userKey).' has been successfully activated';
}else{$signup->pinValidity($pin);}

	return;
}


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

	$title = sanitize($_POST['title']);
	$doc = str_replace(" ", "-", $_FILES['doc']['name']);
	define('upload', 'train/');
	if(isset($title) AND isset($doc) AND strlen($doc)>5 AND strlen($title)>5){
	$success = move_uploaded_file($_FILES['doc']['tmp_name'], upload.$doc);
	

$sqlw = $db->query("INSERT INTO course (title,file) VALUES ('$title','$doc') ");
$report = 'Course Material Successfully Uploaded!';
}else{$report = 'You have entered an incomplete information'; $count=1;}
return;
}




	function pinMultiple($username){
		global $db;
	$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error());
	$row = mysqli_fetch_assoc($sql); $pin = $row['pin'];
	$sq=$db->query("SELECT * FROM user WHERE pin = '$pin' " )or die(mysqli_error());

return mysqli_num_rows($sq);
	}

		function pinMultiple2($username){
		global $db;
		$list=''; $a=1;
	$sql=$db->query("SELECT * FROM user WHERE user = '$username' " )or die(mysqli_error());
	$row = mysqli_fetch_assoc($sql); $pin = $row['pin'];
	$sq=$db->query("SELECT * FROM user WHERE pin = '$pin' " )or die(mysqli_error());
while($ro = mysqli_fetch_assoc($sq)){ $b = $a++; $list .= '<p>'.$b.'. '.$ro['pin'].' '.$ro['user'].'</p>';  }
return $list;
	}


function updateUser2(){
	global $db,$report;
	$keys = $_GET['u-ref'];
$state=sanitize($_POST['state']);
$email=sanitize($_POST['email']);
$lastname=sanitize($_POST['lastname']);
$city=sanitize($_POST['city']);
$address=addslashes(sanitize($_POST['address']));
$phone=sanitize($_POST['phone']);
$bank=sanitize($_POST['bank']);
$accountno=sanitize($_POST['accountno']);


$db->query("UPDATE user SET lastname='$lastname', state='$state', city='$city', phone='$phone', address='$address', bank='$bank', email='$email', accountno='$accountno' WHERE sha1(sn) = '$keys' "); 
$report = 'User Information Successfully Updated!';

	return;
}

function updatePhoto(){
	global $db,$report,$userKey; 

	  $name = $this->userName('user').$_FILES['image']['name'];
	  define('upload', 'photo/');
	 $success = move_uploaded_file($_FILES['image']['tmp_name'], upload.$name);

$sqlw = $db->query("UPDATE user SET photo = '$name' WHERE id = '$userKey' ");
$report = 'User Profile Photo Successfully Update!';
return;
}

function updatePhoto2(){
	global $db,$report; 
$keys = $_GET['u-ref'];
	  $name = 'a'.date('ymdhis').$_FILES['image']['name'];
	  define('upload', 'photo/');
	 $success = move_uploaded_file($_FILES['image']['tmp_name'], upload.$name);

$sqlw = $db->query("UPDATE user SET photo = '$name' WHERE sha1(sn) = '$keys' ");
$report = 'User Profile Photo Successfully Update!';
return;
}


function changePassword(){
	global $db,$report,$count,$userKey;
	$pa = $this->userName('pass');
	  $currentpass = md5($_POST['currentpass']);
	  $newpass = md5($_POST['newpass']);
	  $newpass2 = md5($_POST['newpass2']);
	  
	  if($pa==$currentpass){
		  if($newpass==$newpass2){$db->query("UPDATE user SET pass='$newpass' WHERE id = '$userKey' "); $report = 'User Password Successfully Changed!';}else{$report='New Password Mismatch, Try Again'; $count = 1;}
		  
	  }else{$report='Password Mismatch, Try Again'; $count = 1;}

return;	  
}




function changePassword2(){
	global $db,$report,$count;
	$keys = $_GET['u-ref'];
	$pa = $this->userName('pass');
	  $currentpass = md5($_POST['currentpass']);
	  $newpass = md5($_POST['newpass']);
	  $newpass2 = md5($_POST['newpass2']);
	  
	  if($pa==$currentpass){
		  if($newpass==$newpass2){$db->query("UPDATE user SET pass='$newpass' WHERE sha1(sn) = '$keys' "); $report = 'User Password Successfully Changed!';}else{$report='New Password Mismatch, Try Again'; $count = 1;}
		  
	  }else{$report='Password Mismatch, Try Again'; $count = 1;}

return;	  
}




	//Genrating Row Data
function userName($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']);}
}	
	
	
	//Total Downlines
		function Downlines(){
				global $db,$userKey;
				$randomKey = $this->userName('sn');
			$a = 1;  $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("select * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			$nu += mysqli_num_rows($qu);	
			}
			return $nu;	
			}
			
		//Total Sponsored by User				
	function Sponsored(){
			global $db;
			$randomKey = $this->userName('sn');
			$qu=$db->query("select * FROM user WHERE sponsor = '$randomKey' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			return $nu;	
			}





			
			//Points Generated By User
	function Point(){
		return ($this->Sponsored()*$this->sponsorpoint) + $this->Downlines();
	}

function teamPoint(){
		return $this->Downlines();
	}


	function sponsorPoint(){
		return $this->Sponsored()*$this->sponsorpoint;
	}
	
	function levelRate(){
		return ($this->Level()*100)+$this->pointrate;
	}

	//Loanable Amount
	function Potential(){
		return $this->Point()*$this->levelRate();
	}



	
	function Gen($e){
		global $db;
		$randomKey = $this->userName('sn');
		$gen = 'a'.$e;
		$q=$db->query("SELECT * FROM user WHERE $gen ='$randomKey' " )or die(mysqli_error());
		return mysqli_num_rows($q);
	}


	function wildGen($key,$e){
		global $db;
		$gen = 'a'.$e;
		$q=$db->query("SELECT * FROM user WHERE $gen ='$key' " )or die(mysqli_error());
		return mysqli_num_rows($q);
	}


		function legGen($e,$leg){
		global $db;
		$e = ($e>0) ? $e : 1;
		$randomKey = $this->legKey($leg);
		$gen = 'a'.$e;
		$q=$db->query("SELECT * FROM user WHERE $gen ='$randomKey' " );
		return mysqli_num_rows($q);
	}

//User Stage level
function Level($t=''){
		global $db;
				$randomKey = $this->userName('sn');

				$sql=$db->query("SELECT * FROM user WHERE a1 = '$randomKey' " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);	

			$a = 1;  $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; $target = MATRIX**$b;
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			if($num<MATRIX){$level=0; $targ=MATRIX;}elseif($nu==$target){$level=$b; $targ=$target;}
			}

			if($level<=1){$stagelevel=0;}
			elseif($level==2){$stagelevel=1;}
			elseif($level==3){$stagelevel=0;}
			elseif($level==4){$stagelevel=1;}
			elseif($level==5){$stagelevel=2;}
			elseif($level==6){$stagelevel=0;}
			elseif($level==7){$stagelevel=1;}
			elseif($level==8){$stagelevel=2;}
			elseif($level==9){$stagelevel=0;}
			elseif($level==10){$stagelevel=1;}
			elseif($level==11){$stagelevel=2;}
			elseif($level==12){$stagelevel=0;}
			elseif($level==13){$stagelevel=1;}
			elseif($level==14){$stagelevel=2;}
			elseif($level==15){$stagelevel=0;}
			elseif($level==16){$stagelevel=1;}
			elseif($level==17){$stagelevel=2;}
			elseif($level==18){$stagelevel=0;}
			elseif($level==19){$stagelevel=1;}
			elseif($level==20){$stagelevel=2;}
			elseif($level==21){$stagelevel=0;}

			//stg = stages counting from 1;
			if($this->Sponsored() < 2){$stage='Waiting'; $stg=1; $nextstagelevel=1; }elseif($level<1){$stage='Waiting'; $stg=1; $nextstagelevel=1; }elseif($level<3){$stage='Induct';  $stg=2; $nextstagelevel=3;}elseif($level<6){$stage='Stage 1';  $stg=3; $nextstagelevel=6;}
			elseif($level<9){$stage='Stage 2';  $stg=4; $nextstagelevel=9;}elseif($level<12){$stage='Stage 3';  $stg=5; $nextstagelevel=12;}elseif($level<15){$stage='Stage 4';  $stg=6; $nextstagelevel=15;}elseif($level<18){$stage='Stage 5';  $stg=7; $nextstagelevel=18;}elseif($level<21){$stage='Stage 6';  $stg=8; $nextstagelevel=21;}
			if($t==1){return $stage;}elseif($t==2){return $stg;}elseif($t==3){return MATRIX**($level+1);}elseif($t==4){return $nextstagelevel;}elseif($t==5){return $stagelevel;}elseif($t==7){return $stage.','.$stagelevel;}else{ return $level;}

}



function findLevel($key){
global $db;
$a = 1;   $level=1;
			while($a<=16){$b = $a++;
$nu = 0;
$gen = 'a'.$b; $target = MATRIX**$b;
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$key' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){	
			
			if($this->wildSponsored($row['sn'])>1){$nu += 1; }
if($nu==$target){if($this->wildSponsored($key)>1){ $level = $b+1; }else{ $level = $b+1;}}
		}
	}
	if($this->wildSponsored($key)<2){ $level = 0; }
		return $level;
}


/*
function findLevelx($key){
global $db;
//$key = $this->userName('sn'); 
$lkey = $key;
$level = 0;  
$prog=1;
$a = 1;   //$sq=$db->query("SELECT * FROM levels " );
			while($a <= 10){$b = $a++;

$gen = 'a'.$b; $target = (MATRIX**$b)/2;
			//$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND active = 2 " )or die(mysqli_error());
				if($b==1){$m=0;}elseif($b==2){$m=1;} else{$m=(MATRIX**($b-3)); }
			if($this->legL($this->wildLegKey($lkey))-$m >= $target AND $this->legL($this->wildLegKey($lkey,1))-$m >= $target AND $prog==1){$level += 1; $prog=1; }else{$prog=0;} 
		}

		$levels = ($this->wildSponsored($key)>1) ? $level+1 : 0;

		return $levels;
}
*/


function findLevelx($key){
global $db;
//$key = $this->userName('sn'); 
$lkey = $key;
$level=0;
$left = $this->legL($this->wildLegKey($lkey));
$right = $this->legL($this->wildLegKey($lkey,1));
if($this->wildSponsored($key)>1){$level=1;
if($left >= 3 AND $right >=3){$level=3;}
elseif($left >= 1 AND $right >=1){$level=2;}
	}
return $level;
}


function findLevely($key){
global $db;

$mkey = $key;
$level=3;
$left = $this->countStage1($this->wildLegKey($mkey));
$right = $this->countStage1($this->wildLegKey($mkey,1));

if($left >= 2047 AND $right >=2047){$level=14;}
elseif($left >= 1023 AND $right >=1023){$level=13;}
elseif($left >= 511 AND $right >=511){$level=12;}
elseif($left >= 255 AND $right >=255){$level=11;}
elseif($left >= 127 AND $right >=127){$level=10;}
elseif($left >= 63 AND $right >=63){$level=9;}
elseif($left >= 31 AND $right >=31){$level=8;}
elseif($left >= 15 AND $right >=15){$level=7;}
elseif($left >= 7 AND $right >=7){$level=6;}
elseif($left >= 3 AND $right >=3){$level=5;}
elseif($left >= 1 AND $right >=1){$level=4;}

return $level;
}

/*
function legL($key){
global $db;
$num = ($this->wildSponsored($key)>1) ? 1 : 0;

$a = 1;		
while($a <= 16){$b = $a++;

$gen = 'a'.$b;
if(!empty($key)){
			$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ //$lkey=$r['sn'];
$num += 1; 
//$head .= $r['sn'].',';  
}
	}
		}
		
		return $num;
}
*/


function updateStage1($user){
	global $db;
$sql=$db->query("SELECT * FROM user WHERE user='$user' " )or die(mysqli_error());	
$row = mysqli_fetch_assoc($sql);
$i=1; while($i<=20){ $e=$i++;
$a = 'a'.$e;  $kk = $row[$a];  if($kk>0){
 if($this->verifyStage1($kk) == 1){ $db->query("UPDATE user SET st1=1 WHERE sn='$kk' ");}
}
}
return;
}


function legL($key){
global $db;
$num = 0;


			$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') AND sp > 1 " )or die(mysqli_error());
			$num += mysqli_num_rows($sql);
$num = ($this->wildUserName($key,'sp')>1) ? $num+1 : $num;
		return $num;
}

function countStage1($key){
global $db;
//$num = 0;			
$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' ) AND st1 = 1 " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);	

		$num = ($this->verifyStage1($key) == 1) ? $num+1 : $num;	
		return $num;
}

function verifyStage1($key){
$num = ($this->findLevelx($key) > 2) ? 1 : 0;

return $num;
}

/*
function legSt($key,$st){
global $db,$head;

//$num = ($this->wildLevel2($key,2) >= $st) ? 1 : 0;
$head = ($this->wildLevel2($key,2) >= $st) ? $key.',' : '';

$a = 1;
			while($a <= 16){$b = $a++;

$gen = 'a'.$b;
			$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ $lkey=$r['sn'];
if($this->wildLevel2($lkey,2) >= $st){ //$num += 1;
$head .= $r['sn'].','; }

		}
		}
		
		return $head;
}
*/
function legCount($key,$st){
return	count(explode(',', $this->legSt($key,3)))-1;
}

function legSt($key,$st){
global $db,$head;

//$num = ($this->wildLevel2($key,2) >= $st) ? 1 : 0;
$head = ($this->wildLevel2($key,2) >= $st) ? $key.',' : '';


			$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 a14='$key' OR a15='$key' OR a16='$key' OR a17='$key' OR a18='$key') AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ $lkey=$r['sn'];
if($this->wildLevel2($lkey,2) >= $st){ $head .= $r['sn'].','; }

	
		}
		
		return $head;
}


function stagePro($key,$st){
global $db,$head;

$num = ($this->wildLevel2($key,2) >= $st) ? 1 : 0;


$a = 1;
			while($a <= 16){$b = $a++;

$gen = 'a'.$b;
			$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ $lkey=$r['sn'];
if($this->wildLevel2($key,2) >= $st){ $num += 1; }

		}
		}
		
		return $num;
}


//

function stageProgress($opt=''){
$keys = $this->userName('sn');
$st = $this->wildLevel2($keys,2);

$left = count(explode(',',$this->legSt($this->legKey(),$st)))-1;
$right = count(explode(',',$this->legSt($this->legKey(1),$st)))-1;
//$left = $this->stagePro($this->wildLegKey($keys),$st);
//$right = $this->stagePro($this->wildLegKey($keys,1),$st);

if($st>1){
if($st==2){$max=3;}else{$max=7;}
$leftp = $left/$max*50;
$leftp = ($leftp>50)?50:$leftp;
$rightp = $right/$max*50;
$rightp = ($rightp>50)?50:$rightp;
}else{$leftp = ($this->wildSponsored($keys)>0)?50:0; $rightp=0;}
if($opt==1){ return number_format($leftp,1).'%'; }
elseif($opt==2){ return number_format($rightp,1).'%'; }
else{ 	return number_format($rightp+$leftp,1).'%'; }

}

/*
function legH($key){
global $db;

$head = ($this->wildSponsored($key)>1) ? $key.',' : '';
$a = 1;//sq=$db->query("SELECT * FROM levels " );
			while($a <= 16){$b = $a++;

$gen = 'a'.$b;
			$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ $lkey=$r['sn'];
//$num += 1; 
$head .= $r['sn'].',';
		}
		}
		
		return $head;
}*/
function legH($key){
global $db;

$head = ($this->wildUserName($key,'sp')>1) ? $key.',' : '';

			$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') AND sp > 1 " )or die(mysqli_error());
			while($r = mysqli_fetch_assoc($sql)){ $lkey=$r['sn'];
//$num += 1; 
$head .= $r['sn'].',';
		}
		
		return $head;
}

/*
function findLevelx($key){
global $db;
//$key = $this->userName('sn'); 
$level = 0;  $prog=1;
$a = 1;   $sq=$db->query("SELECT * FROM levels " );
			while($row = mysqli_fetch_assoc($sq)){$b = $a++;

$gen = 'a'.$b; $target = MATRIX**$b;
			$sql=$db->query("SELECT * FROM user WHERE $gen = '$key' AND active = 2 " )or die(mysqli_error());

			if($this->CheckSponsor($sql)==$target AND $prog==1){$level += 1; $prog=1; }else{$prog=0;} 
		}
		$levels = ($this->wildSponsored($key)>1) ? $level+1 : $level;
		return $levels;
}
*/

function CheckSponsor($sql){
	$num=0;
while($row = mysqli_fetch_assoc($sql)){ 
if($this->wildSponsored($row['sn'])>1){$num += 1; }
 }
return $num;	
}

//User Stage level
function wildLevel2($key,$t=''){
		global $db;
		
			$level = ($this->verifyStage1($key) == 0) ? $this->findLevelx($key) : $this->findLevely($key);

			
			if($level==0){$stagelevel=0; $stage='Waiting'; $stg=1; $nextstagelevel=1;  }
			elseif($level==1){$stagelevel=0; $stage='Induct'; $stg=2; $nextstagelevel=3; }
			elseif($level==2){$stagelevel=1; $stage='Induct'; $stg=2; $nextstagelevel=3; }
			elseif($level==3){$stagelevel=0; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==4){$stagelevel=1; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==5){$stagelevel=2; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==6){$stagelevel=0; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==7){$stagelevel=1; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==8){$stagelevel=2; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==9){$stagelevel=0; $stage='Stage 3'; $stg=5; $nextstagelevel=12; }
			elseif($level==10){$stagelevel=1; $stage='Stage 3'; $stg=5; $nextstagelevel=12;}
			elseif($level==11){$stagelevel=2; $stage='Stage 3'; $stg=5; $nextstagelevel=12;}
			elseif($level==12){$stagelevel=0; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==13){$stagelevel=1; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==14){$stagelevel=2; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==15){$stagelevel=0; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==16){$stagelevel=1; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==17){$stagelevel=2; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==18){$stagelevel=0; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==19){$stagelevel=1; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==20){$stagelevel=2; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==21){$stagelevel=0;}

			//$count = $this->legCount($key,$stg);
			//$stg = ($stg > 3 AND $count < 15)?$stg-1:$stg;
		
			if($t==1){return $stage;}elseif($t==2){return $stg;}elseif($t==3){return MATRIX**($level+1);}elseif($t==4){return $nextstagelevel;}elseif($t==5){return $stagelevel;}elseif($t==7){return $stage.','.$stagelevel;}else{return $level;}

}




function matrixAward(){
	global $db;
$randomKey = $this->userName('sn');
$level = $this->wildLevel2($randomKey)+1;
$award = 0;
$sql = $db->query("SELECT * FROM levels WHERE sn <= '$level' ");
while ($row=mysqli_fetch_assoc($sql)) {
	$award += (int)$row['award'];
}
	return $award;
}


function wildSponsored($key){
			global $db,$user;
			$qu=$db->query("select * FROM user WHERE sponsor = '$key' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			return $nu;	
			}






//Wild User Stage/level statistics
function wildLevel($key,$t=''){
		global $db;
		
			$level = $this->findLevelx($key);

				if($level==0){$stagelevel=0; $stage='Waiting'; $stg=1; $nextstagelevel=1; }
			elseif($level==1){$stagelevel=0; $stage='Induct';  $stg=2; $nextstagelevel=3; }
			elseif($level==2){$stagelevel=1; $stage='Induct';  $stg=2; $nextstagelevel=3; }
			elseif($level==3){$stagelevel=0; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==4){$stagelevel=1; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==5){$stagelevel=2; $stage='Stage 1'; $stg=3; $nextstagelevel=6; }
			elseif($level==6){$stagelevel=0; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==7){$stagelevel=1; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==8){$stagelevel=2; $stage='Stage 2'; $stg=4; $nextstagelevel=9; }
			elseif($level==9){$stagelevel=0; $stage='Stage 3'; $stg=5; $nextstagelevel=12; }
			elseif($level==10){$stagelevel=1; $stage='Stage 3'; $stg=5; $nextstagelevel=12;}
			elseif($level==11){$stagelevel=2; $stage='Stage 3'; $stg=5; $nextstagelevel=12;}
			elseif($level==12){$stagelevel=0; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==13){$stagelevel=1; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==14){$stagelevel=2; $stage='Stage 4'; $stg=6; $nextstagelevel=15;}
			elseif($level==15){$stagelevel=0; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==16){$stagelevel=1; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==17){$stagelevel=2; $stage='Stage 5'; $stg=7; $nextstagelevel=18;}
			elseif($level==18){$stagelevel=0; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==19){$stagelevel=1; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==20){$stagelevel=2; $stage='Stage 6'; $stg=8; $nextstagelevel=21;}
			elseif($level==21){$stagelevel=0;}

			//stg = stages counting from 1;
		
			if($t==1){return $stage;}elseif($t==2){return $stg;}elseif($t==3){return MATRIX**($level+1);}elseif($t==4){return $nextstagelevel;}elseif($t==5){return $stagelevel;}elseif($t==7){return $stage.','.$stagelevel;}else{return $level;}


}







function legLevel($leg,$t=''){
		global $db;
				$randomKey = $this->legKey($leg);

				$sql=$db->query("SELECT * FROM user WHERE a1 = '$randomKey' " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);	

			$a = 1;  $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; $target = MATRIX**$b;
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			if($num<MATRIX){$level=0; $targ=MATRIX;}elseif($nu==$target){$level=$b; $targ=$target;}
			}

			if($level<=1){$stagelevel=0;}
			elseif($level==2){$stagelevel=1;}
			elseif($level==3){$stagelevel=0;}
			elseif($level==4){$stagelevel=1;}
			elseif($level==5){$stagelevel=2;}
			elseif($level==6){$stagelevel=0;}
			elseif($level==7){$stagelevel=1;}
			elseif($level==8){$stagelevel=2;}
			elseif($level==9){$stagelevel=0;}
			elseif($level==10){$stagelevel=1;}
			elseif($level==11){$stagelevel=2;}
			elseif($level==12){$stagelevel=0;}
			elseif($level==13){$stagelevel=1;}
			elseif($level==14){$stagelevel=2;}
			elseif($level==15){$stagelevel=0;}
			elseif($level==16){$stagelevel=1;}
			elseif($level==17){$stagelevel=2;}
			elseif($level==18){$stagelevel=0;}
			elseif($level==19){$stagelevel=1;}
			elseif($level==20){$stagelevel=2;}
			elseif($level==21){$stagelevel=0;}

			//stg = stages counting from 1;
			if($level<1){$stage='WAITING'; $stg=1; $nextstagelevel=1;}elseif($level<3){$stage='Induct';  $stg=2; $nextstagelevel=3;}elseif($level<6){$stage='STAGE 1';  $stg=3; $nextstagelevel=6;}
			elseif($level<9){$stage='STAGE 2';  $stg=4; $nextstagelevel=9;}elseif($level<12){$stage='STAGE 3';  $stg=5; $nextstagelevel=12;}elseif($level<15){$stage='STAGE 4';  $stg=6; $nextstagelevel=15;}elseif($level<18){$stage='STAGE 5';  $stg=7; $nextstagelevel=18;}elseif($level<21){$stage='STAGE 6';  $stg=8; $nextstagelevel=21;}
			if($t==1){return $stage;}elseif($t==2){return $stg;}elseif($t==3){return MATRIX**($level+1);}elseif($t==4){return $nextstagelevel;}elseif($t==5){return $stagelevel;}else{ return $level;}

}







function levelScore(){
	$lev=$this->Level()+1; 
	return $this->Gen($lev);
}


function levelTarget(){
	return $this->Level(3);
}




function stageLevelScore(){
	$lev=$this->Level(4); 
	return $this->Gen($lev);
}


function stageLevelTarget(){
	return MATRIX**($this->Level(4));//$this->Level(3);
}

function stageLevelProgress(){
	//$pro = ($this->stageLevelScore()*100)/$this->stageLevelTarget();
	//if($this->Sponsored()==0){$pro = 0;}elseif($this->Sponsored()==1){$pro = 50;}
	return 0;//number_format($this->gTree(1),1).'%';
}


//leg statistics
function legStageLevelScore($leg){
	$lev = $this->Level(4)-1; 
	return $this->legGen($lev,$leg);
}


function legStageLevelTarget(){
	return $this->stageLevelTarget()/2 ;//$this->Level(3);
}

function legStageLevelProgress($leg){
	global $directdown;
	$pro = ($this->legStageLevelScore($leg) > 0) ? ($this->legStageLevelScore($leg)*100)/$this->legStageLevelTarget($leg) : 0;
	if($this->Sponsored()<2){ return '0.0%';}
	elseif($directdown==0){ return '0.0%';}elseif($directdown==1 && $leg==1){ return '0.0%';}elseif($directdown==1 && $leg==0){ return '100.0%';}else{
	return number_format($pro,1).'%';}
}




function proLevel($leg,$t=''){
		global $db;
		$randomKey = $this->legKey($leg);

				$sql=$db->query("SELECT * FROM user WHERE a1 = '$randomKey' " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);	

			$a = 1;  $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; $target = MATRIX**$b;
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			$nu = mysqli_num_rows($qu);	
			if($num<MATRIX){$level=0; $targ=MATRIX;}elseif($nu==$target){$level=$b; $targ=$target;}
			}
			if($level<1){$stage='WAITING'; $stg=1;}elseif($level<3){$stage='Induct';  $stg=2;}elseif($level<6){$stage='STAGE 1';  $stg=3;}
			elseif($level<9){$stage='STAGE 2';  $stg=4;}elseif($level<12){$stage='STAGE 3';  $stg=5;}elseif($level<15){$stage='STAGE 4';  $stg=6;}elseif($level<18){$stage='STAGE 5';  $stg=7;}elseif($level<21){$stage='STAGE 6';  $stg=8;}
			if($t==1){return $stage;}elseif($t==2){return $stg;}else{ return $level;}

}


//stage
function Stage(){
	return $this->wildLevel2($this->userName('sn'),1);
}

function totalEarning(){
	return $this->matrixAward()+$this->referalB();
}

function Balance(){
	return $this->totalEarning()-$this->totalWithdraw()-$this->totalPending()+$this->transfered(2)-$this->transfered();
}

function totalWithdraw(){
	global $db,$userKey;
	$id=$this->userName();
	$amt = 0;
	$sq=$db->query("SELECT * FROM withdraw WHERE id='$userKey' AND status = 1 " );
			while($row = mysqli_fetch_assoc($sq)){
			$amt += $row['amount'];
			} 
	return $amt;
}


function totalPending(){
	global $db,$userKey;
	$id=$this->userName();
	$amt = 0;
	$sq=$db->query("SELECT * FROM withdraw WHERE id='$userKey' AND status = 0 " );
			while($row = mysqli_fetch_assoc($sq)){
			$amt += $row['amount'];
			} 
	return $amt;
}

function Stage1(){
	return $this->Level(2);
}

//leg 0=left, 1=right
function legKey($leg=0){
global $db,$directdown;
$key = '';
		$randomKey = $this->userName('sn');
		$qu=$db->query("SELECT * FROM user WHERE a1 ='$randomKey' ORDER BY sn ASC" )or die(mysqli_error());
		$directdown = mysqli_num_rows($qu);
		while($row = mysqli_fetch_assoc($qu)){
				$key .= $row['sn'].",";
				}
				$key = explode(",", $key);
			//	$left = $key[0];
			//	$right = $key[1];
				$legkey = !empty($key[$leg]) ? $key[$leg] : '';
		return $legkey;
}



//leg 0=left, 1=right
function wildLegKey($lkey,$leg=0){
global $db,$directdown;
$key = '';
		$qu=$db->query("SELECT * FROM user WHERE a1 ='$lkey' ORDER BY sn ASC" )or die(mysqli_error());
		$directdown = mysqli_num_rows($qu);
		while($row = mysqli_fetch_assoc($qu)){
				$key .= $row['sn'].",";
				}
				$key = explode(",", $key);
			//	$left = $key[0];
			//	$right = $key[1];
				$legkey = !empty($key[$leg]) ? $key[$leg] : '';
		return $legkey;
}

function legTable(){
	global $user;
$user = $this->legKey();
$key = '<tr><td>Left</td><td>'.$this->userNameWild().'</td>
                                            <td>'.$this->userNameWild('user').'</td></tr>';
$user = $this->legKey(1);
$key .= '<tr><td>Right</td><td>'.$this->userNameWild().'</td>
                                            <td>'.$this->userNameWild('user').'</td></tr>';
return $key;}


function userNameWild($col=''){
				global $db,$user;
				
			$que=$db->query("SELECT * FROM user WHERE sn = '$user' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);	
				if(!empty($col)){return $ro[$col];}
				else{return $ro['firstname'];}
}

function uName($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 uNameUser($user,$col='user'){
				global $db;
				
			$que=$db->query("SELECT * FROM user WHERE user = '$user' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);	
return $ro[$col];			
}

function courseName($id,$col='title'){
				global $db;
				
			$que=$db->query("SELECT * FROM course WHERE sn = '$id' " )or die(mysqli_error());
					$ro=mysqli_fetch_array($que);	
return $ro[$col];			
}	




	function chartMonth(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = date("M", mktime(0, 0, 0, $b, 10));
			$range .= "'".$c."', ";
			}
			return $range;
	}


//chart data of total entry per 
	function monthEntryData(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = $this->monthDownlines($b);
			$range .= $c.', ';
			}

			return $range;
	}


//chart data of total entry per 
	function monthChartData(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = $this->monthlyRegistered($b);
			$range .= $c.', ';
			}

			return $range;
	}


	//chart data of total entry per 
	function monthEntryDataTotal(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = $this->entryPerMonth($b);
			$range .= $c.', ';
			}

			return $range;
	}


//chart data of user monthly sponsor
		function monthUserSponsor(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = $this->sponsorPerMonth($b);
			$range .= $c.', ';
			}

			return $range;
	}




	//chart data of user monthly sponsor
		function monthUserInducted(){
		$range = '';
		$cm = date('m');
		$a = $cm-5; 
			while($a<=$cm){ $b=$a++; $c = $this->inductedPerMonth($b);
			$range .= $c.', ';
			}

			return $range;
	}

//maximum monthly entry// $tim = max(explode(",", $profile->monthUserSponsor()));
	function maxMonthly(){
		$max = max(explode(",", $this->monthEntryData()));
		return $max;
	}


	function maxMonthlyAll(){
		$max = max(explode(",", $this->monthChartData()));
		return $max;
	}



	//maximum monthly entry total for all users //
	function maxMonthlyTotal(){
		$max = max(explode(",", $this->monthEntryDataTotal()));
		return $max;
	}

//Calculate total monthly entry
function entryPerMonth($month){
	global $db;
	$num = 0;
	$sql=$db->query("select * FROM user " )or die(mysqli_error());
	while($row = mysqli_fetch_assoc($sql)){
$tim = (int)substr($row['created'],5,2); 
if($tim==$month){$num += 1;	}
}
return $num;
}



		function monthDownlines($month){
				global $db,$userKey;
				$randomKey = $this->userName('sn');
			$a = 1;  $num = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; 
			$sql=$db->query("select * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){
$tim = (int)substr($row['created'],5,2); 
if($tim==$month){$num += 1;	}
}	
			}
			return $num;	
			}


		function monthlyRegistered($month){
				global $db;
				
			$num = 0;

			$sql=$db->query("SELECT * FROM user " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){
$tim = (int)substr($row['created'],5,2); 
if($tim==$month){$num += 1;	}
}	

			return $num;	
			}





//Calculate the amunt of members sponsored by a user monthly
function sponsorPerMonth($month){
	global $db;
	$randomKey = $this->userName('sn');
	$num = 0;
	$sql=$db->query("SELECT * FROM user WHERE sponsor = '$randomKey' " )or die(mysqli_error());
	while($row = mysqli_fetch_assoc($sql)){
$tim = (int)substr($row['created'],5,2); 
if($tim==$month){$num += 1;	}
}
return $num;
}


//Calculate the amunt of members sponsored by a user monthly
function inductedPerMonth($month){
	global $db;
	$num = 0;
	$sql=$db->query("SELECT * FROM user " )or die(mysqli_error());
	while($row = mysqli_fetch_assoc($sql) ){
$tim = (int)substr($row['created'],5,2); 
if($tim==$month && $this->wildSponsored($row['sn'])>1){$num += 1;	}
}
return $num;
}



//Count all registered users
function allUsers(){
	global $db;

	$sql=$db->query("SELECT * FROM user " )or die(mysqli_error());
	$num = mysqli_num_rows($sql);
return $num;
}



//Calculate the amunt of members sponsored by a user monthly
function allInductedUsers(){
	global $db;

	$sql=$db->query("SELECT * FROM user WHERE sp>1 " )or die(mysqli_error());
	$num = mysqli_num_rows($sql);
return $num;
}

//referral table
	function Referrals(){
			global $db;
			$randomKey = $this->userName('sn');
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Full Name</th>
                                            <th>username</th>
                                            
                                            <th>Phone Number</th>
                                            <th>Location</th>
                                            <th>Join on</th>
                                            <th>Stage</th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
$i=1;
			$sql=$db->query("select * FROM user WHERE sponsor = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){ $e=$i++;
				$mark = ($this->wildSponsored($row['sn'])<2) ? '*' : '';
				$table .= ' <tr>
                                            <td>'.$e.'</td>
                                            <td>'.$row['firstname'].' '.$row['lastname'].'</td>
                                            <td>'.$row['user'].'</td>
                                            
                                            <td>'.$row['phone'].'</td>
                                            <td>'.$row['city'].', '.$row['state'].'</td>
                                             <td>'.date('d M, Y',strtotime($row['created'])).'</td>
                                               <td>'.$mark.$this->wildLevel2($row['sn'],7).'</td>
                                        </tr>';
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}




///waiting List

				function waitingList($no=3){
				global $db,$key;
				$randomKey = $this->userName('sn');
				$key='';
			$a = 1; $x = 1; $c=0; $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' AND active < 2 " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu) AND $c<$no){
				$c = $x++;
				$key .= '<tr><td>'.$row['firstname'].'</td>
                                            <td>'.$row['user'].'</td></tr>';
                                        
				
			}	
			}
			return $key;	
			}




function recentlyRegistered(){
				global $db;

				$key='';
			 $c=0; $nu = 0;
	
			$qu=$db->query("SELECT * FROM user ORDER BY sn DESC LIMIT 7 " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
				
				$key .= '<tr><td><a href="javascript:void(0);" class="text-link">'.$row['firstname'].'</a></td>
                                            <td>'.$row['user'].'</td></tr>';
                                        
		
			}
			return $key;	
			}



	function waitingList2($no=20){
				global $db,$key;
				$randomKey = $this->userName('sn');
				$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Full Name</th>
                                            <th>username</th>
                                            
                                            <th>Phone Number</th>
                                            <th>Location</th>
                                            <th>Join on</th>
                                            
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
			$a = 1; $x = 1; $c=0; $nu = 0;
			while($a<=16){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' AND active < 2 " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu) AND $c<$no){
				$c = $x++;
				$table .= ' <tr>
                                            <td>'.$c.'</td>
                                            <td>'.$row['firstname'].' '.$row['lastname'].'</td>
                                            <td>'.$row['user'].'</td>
                                            
                                            <td>'.$row['phone'].'</td>
                                            <td>'.$row['city'].', '.$row['state'].'</td>
                                             <td>'.date('d M, Y',strtotime($row['created'])).'</td>
                                        </tr>';
                                        
				
			}	
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}







			function showMypin(){
			global $db,$userKey,$signup;	
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>E-PIN</th>
                                                                <th>PIN Date</th>
                                                                <th>Type</th>
                                                                <th>Status</th>
                                                                <th>Recipient</th>
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>';
            $sql = $db->query("SELECT * FROM pin WHERE rep='$userKey' ORDER BY sn DESC"); $i=1;
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                            $user = $row['id'];
                                            if($row['status']==1){$st='used'; }else{$st='active';}
                                              if($row['tm']=='Request'){$type='Request'; }else{$type='Auto';}
                                        $uname = ($row['status']==1)?' ('.$this->uNameUser($user).')':'';
                                    $table .= '<tr>
                                      <td >'.$e.'</td>
                                      <td  ><a href="#">'.$row['pin'].'</a></td>
                                      <td >'.$row['created'].'</td>
                                      <td >'.$row['tm'].'</td>
                                        <td >'.$st.'</td>
                                     <td >'.$this->uNameUser($user,'firstname').' '.$this->uNameUser($user,'lastname').$uname.'</td>
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}




function showMypinRequest(){
			global $db,$userKey;	
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Number of PINs</th>
                                                                <th>Payment Details</th>
                                                                <th>Date</th>
                                                                <th>Status</th>
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>';
            $sql = $db->query("SELECT * FROM payment WHERE id='$userKey' "); $i=1;
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                           
                                            if($row['status']==1){$st=$row['buy'].' Approved'; }else{$st='Pending';}
                                    $table .= '<tr>
                                      <td >'.$e.'</td>
                                      <td  ><a href="#">'.$row['qty'].'</a></td>
                                      <td >'.$row['details'].'</td>
                                      <td >'.$row['created'].'</td>
                                      <td >'.$st.'</td>
                                    
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}






function viewPinRequest(){
			global $db;	
			$table = '<table id="" class="table-bordered display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Username</th>
                                                                <th>Number of PINs</th>
                                                                <th>Payment Details</th>
                                                                <th>Date</th>
                                                                <th>Status</th>
                                                                <th>Action</th>
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>';
                                    $col = '';
            $sql = $db->query("SELECT * FROM payment ORDER BY status ASC, created DESC LIMIT 50 "); $i=1;
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                           
                                            if($row['status']==1){$st=$row['buy'].' Approved'; $btn='';}else{$st='Pending';   $btn='<button type="submit" class="btn btn-xs btn-primary" name="processPin" value="'.$row['sn'].'">Process</button>';}
                                         // if(isset($_SESSION['processPin'])){  
                                            $col = ($_SESSION['processPin']==$row['sn'])?' bgcolor="#FF66CC"':'';
                                           
                                         // }
                                    $table .= '<tr '.$col.'>
                                      <td >'.$e.'</td>
                                      <td >'.$this->uName($row['id']).'</td>
                                      <td  ><a href="#">'.$row['qty'].'</a></td>
                                      <td >'.$row['details'].'</td>
                                      <td >'.$row['created'].'</td>
                                      <td >'.$st.'</td>
                                      <td >'.$btn.'</td>
                                    
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}














			function showMywithdraw(){
			global $db,$userKey,$signup;	
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Transaction ID</th>
                                                                <th>Amount</th>
                                                                <th>Balance</th>
                                                                <th>Transaction Date</th>
                                                                <th>Transaction</th>
                                                                <th>Type</th>
                                                                <th>Status</th>
                                                                
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>'; $i=1;
           $sql = $db->query("SELECT * FROM withdraw WHERE id='$userKey' ORDER BY sn ASC ");
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                           
                                            if($row['status']==1){$st='Complete'; }else{$st='Pending';}
                                            $type = ($row['finalbalance']>$row['inibalance']) ? 'Credit' : 'Debit';
                                    $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td >'.$row['tno'].'</td>
                                     <td  ><a href="#">$'.$row['amount'].'</a></td>
                                      <td  ><a href="#">$'.$row['finalbalance'].'</a></td>
                                      <td >'.$row['created'].'</td>
                                      <td >'.$row['type'].'</td>
                                      <td >'.$type.'</td>
                                      <td >'.$st.'</td>
                                     
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}







			function showMyawards(){
			global $db,$userKey;
			$randomKey = $this->userName('sn');
			$level = $this->wildLevel2($randomKey)+1;	
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Stage</th>
                                                                <th>Level</th>
                                                                <th>Award</th>
                                                                <th>type</th>
                                                                <th>Status</th>
                                                                
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>'; $e=0;
           $sql = $db->query("SELECT * FROM levels WHERE sn <='$level' ORDER BY sn ASC ");
                                        while($row = mysqli_fetch_assoc($sql)){    
                                    if(!empty($row['award'])){     $e += 1;
                                    $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td >'.$row['title'].'</td>
                                     <td  ><a href="#">'.$row['level'].'</a></td>
                                      <td ><a href="#">$'.$row['award'].'</a></td>
                                     <td ><a href="#">Cash Bonus</a></td>
                                      <td ></td>
                                     
                                    </tr>';  }


                                    if(!empty($row['award2'])){ $sn = $row['sn'];
                                    	$sq = $db->query("SELECT * FROM award WHERE level='$sn' AND id='$userKey' "); $rr=mysqli_fetch_assoc($sq);
if(mysqli_num_rows($sq)==0){
                                    	$action = '<form method="post"><button type="submit" name="requestIncentive" class="btn btn-primary btn-xs" value="'.$row['sn'].'">Request</button></form>'; }elseif(mysqli_num_rows($sq)==1 AND $rr['remark']==0){$action='Pending';}else{$action='Supplied'; }

                                    		$e += 1;
                                   $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td >'.$row['title'].'</td>
                                     <td  ><a href="#">'.$row['level'].'</a></td>
                                      <td ><a href="#">'.$row['award2'].'</a></td>
                                     <td ><a href="#">Incentive</a></td>
                                      <td >'.$action.'</td>
                                     
                                    </tr>';
                                     }  
                                    }

                                        $sql = $db->query("SELECT * FROM user WHERE sponsor = '$randomKey' ORDER BY sn ASC ");
                                        while($row = mysqli_fetch_assoc($sql)){    
                                     $e += 1;
                                    $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td ></td>
                                     <td  ><a href="#"></a></td>
                                      <td ><a href="#">$2</a></td>
                                     <td ><a href="#">Referal Bonus</a></td>
                                      <td ></td>
                                     
                                    </tr>';  }

                               $table .= '</tbody> </table>';

             return $table;                       
			}


function requestIncentive(){
	global $db, $userKey,$report,$count;
$sn = sanitize($_POST['requestIncentive']);
$sql = $db->query("SELECT * FROM award WHERE level='$sn' AND id='$userKey' ");
if(mysqli_num_rows($sql)>0){$report='Sorry, You have previously requested for this incentive'; $count=1;}
else{ $db->query("INSERT into award (id,level) VALUES ('$userKey','$sn') ");
$report = 'Request successfully submitted';}

	return;
}

	function showAwardee(){
				global $db,$stg;
				$_SESSION['sta']=isset($_POST['stage']) ? sanitize($_POST['stage']) : $_SESSION['sta'];
				$_SESSION['lv']=isset($_POST['level']) ? sanitize($_POST['level']) : $_SESSION['lv'];
				
				$stg = $this->stagetoLevel($_SESSION['sta'],$_SESSION['lv']);
				
				$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Full Name</th>
                                            <th>username</th>
                                            <th>Bank Details</th>
                                            <th>Award</th>
                                            <th>Join on</th>
                                            <th>Status</th>
                                           </tr>
                                    </thead>
                                   
                                    <tbody>';
			$a = 1;
			
			$qu=$db->query("SELECT * FROM user " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
				$id = $this->wildUserName($row['sn'],'id');
				$checkaward = $this->checkAward($_SESSION['sta'],$_SESSION['lv'],$id);
				$award = $this->levelAward($_SESSION['sta'],$_SESSION['lv']);
				if(($stg!=0 && $this->wildLevel2($row['sn'])==$stg && $this->wildSponsored($row['sn'])) OR ($this->wildLevel2($row['sn'])>$stg && $checkaward==0) ){
					$b = $a++;
					
					
					if($checkaward==0){$action = 'Not Awarded';
					//$action = '<input type="hidden" name="amount" value="'.$award.'"> <button type="submit" name="rid" class="btn btn-success btn-xs" value="'.$id.'">Approve Award</button>';
				}else{$action = 'Awarded';}
				if(!empty($award)){
				$table .= ' <tr>
                                            <td>'.$b.'</td>
                                            <td>'.$row['firstname'].' '.$row['lastname'].'</td>
                                            <td>'.$row['user'].'</td>
                                            
                                            <td>'.$row['bank'].' '.$row['accountno'].'</td>
                                            <td>'.$award.'</td>
                                             <td>'.date('d M, Y',strtotime($row['created'])).'</td>
                                             <td>'.$action.'</td>
                                        </tr>';

                                    }  }
	
			}	
			

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}


function showWithdrawRequest(){
			global $db,$userKey,$signup;

			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Transaction ID</th>
                                                                <th>Beneficiary</th>
                                                                <th>Amount</th>
                                                                <th>Balance</th>
                                                                <th>Transaction Date</th>
                                                                <th>Transaction</th>
                                                                <th>Type</th>
                                                                <th>Status</th>
                                                                <th>Action</th>
                                                                
                                                            </tr>
                                    </thead>
                                   
                                    <tbody>'; $i=1;
                                  if(isset($_GET['quser'])){$quser = $this->uNameUser($_GET['quser'],'id'); 
$sql=$db->query("SELECT * FROM withdraw WHERE id='$quser' ORDER BY sn DESC LIMIT 200" )or die(mysqli_error()); }else{
           $sql = $db->query("SELECT * FROM withdraw ORDER BY sn DESC LIMIT 200");
       }
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                           
                                            if($row['status']==1){$st='Complete'; $action = ''; }else{$st='Pending';
                                        $action = '<button type="submit" name="rid" class="btn btn-success btn-xs" value="'.$row['tno'].'">Approve Request</button>';
                                    }
                                            $type = ($row['finalbalance']>$row['inibalance']) ? 'Credit' : 'Debit';

                                     
//

                                    $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td >'.$row['tno'].'</td>
                                      <td><a href="?quser='.$this->uName($row['id']).'">'.$this->uName($row['id']).', '.$this->uName($row['id'],'bank').', '.$this->uName($row['id'],'accountno').'</a></td>
                                     <td  ><a href="#">$'.$row['amount'].'</a></td>
                                      <td  ><a href="#">$'.$row['finalbalance'].'</a></td>
                                      <td >'.$row['created'].'</td>
                                      <td >'.$row['type'].'</td>
                                      <td >'.$type.'</td>
                                      <td >'.$st.'</td>
                                      <td >'.$action.'</td>
                                     
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}

function showIncentiveRequest(){
			global $db,$userKey,$signup;	
			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                      <tr>
                                                                
                                                                <th>SN</th>
                                                                <th>Request ID</th>
                                                                <th>Beneficiary</th>
                                                                <th>Item</th>
                                                            
                                                                <th>Transaction Date</th>
                                                                <th>Transaction Type</th>
                                                                <th>Status</th>
                                                                <th>Action</th>
                                                                
                                                            </tr>
                                    </thead>
                                   		
                                    <tbody>'; $i=1;
           $sql = $db->query("SELECT * FROM award ORDER BY sn DESC LIMIT 200 ");
                                        while($row = mysqli_fetch_assoc($sql)){  $e = $i++; 
                                           
                                            if($row['remark']==1){$st='Complete'; $action = ''; }else{$st='Pending';
                                        $action = '<button type="submit" name="rid" class="btn btn-success btn-xs" value="'.$row['sn'].'">Approve Request</button>';
                                    }
                                            $type = 'Incentive Award';
                                            $alevel = $row['level'];
                                      $sl = $db->query("SELECT * FROM levels WHERE sn='$alevel' ORDER BY sn DESC LIMIT 200 ");
                                     $rw = mysqli_fetch_assoc($sl); $item = $rw['award2'];
                                     


                                    $table .=  '<tr>
                                      <td >'.$e.'</td>
                                      <td >'.$row['sn'].'</td>
                                      <td>'.$this->wildUserKeys($row['id']).', '.$this->wildUserKeys($row['id'],'bank').', '.$this->wildUserKeys($row['id'],'accountno').'</td>
                                     <td  ><a href="#">'.$item.'</a></td>
                                      
                                      <td >'.$row['created'].'</td>
                                 
                                      <td >'.$type.'</td>
                                      <td >'.$st.'</td>
                                      <td >'.$action.'</td>
                                     
                                    </tr>';
                                     }  

                               $table .= '</tbody> </table>';

             return $table;                       
			}

function checkAward($stg,$level,$id){
global $db;
$sql=$db->query("SELECT * FROM levels WHERE stg='$stg' AND level = '$level' " )or die(mysqli_error());
$row=mysqli_fetch_assoc($sql); $alevel = $row['sn'];

$qu=$db->query("SELECT * FROM award WHERE id='$id' AND level = '$alevel' " )or die(mysqli_error());
$num = mysqli_num_rows($qu);
return $num;
}


function countAward($level){
global $db;
$qu=$db->query("SELECT * FROM award WHERE level = '$level' " )or die(mysqli_error());
$num = mysqli_num_rows($qu);
return $num;
}

function levelAward($stg,$level){
global $db;
$award ='';
$qu=$db->query("SELECT * FROM levels WHERE stg='$stg' AND level = '$level' " )or die(mysqli_error());
$row= mysqli_fetch_assoc($qu);
//if(!empty($row['award'])){$award .= $row['award'];}
if(!empty($row['award2'])){$award .= $row['award2'];}
return $award;
}

function approveAward(){
	global $db,$report,$count;
	$id = sanitize($_POST['approveAward']);
	$stg = $_SESSION['sta'];
	$level = $_SESSION['lv'];
	$pa = $this->userName('pass');
	  $approval = md5($_POST['approval']);
 
	  if($pa==$approval){
$msg = $db->query("INSERT INTO award (id,stg,level)
VALUES('$id','$stg','$level')") or die(mysqli_error());
$report = 'User Successfully Awarded!';
}else{$report = 'You have entered an invalid authorization code!'; $count=1;}
	return;
}



function userStatistics(){
	global $db;
	$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Stage</th>
                                             <th>Level</th>
                                             <th>Cash Award</th>
                                             <th>Incentive Award</th>
                                            <th>Count</th>
                                            <th>Awarded</th>
                                            <th>Not Awarded</th>
                                        
                                           </tr>
                                    </thead>
                                   
                                    <tbody>';
			$a = 1;
	$qu=$db->query("SELECT * FROM levels " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
				
					$b = $a++;
					$level = $row['sn']-1;
					//$checkaward = $this->checkAward($_SESSION['sta'],$_SESSION['lv'],$id);
					$number = $this->levelUsers($level);
					$awarded = $this->countAward($row['sn']);
					$notawarded = $number-$awarded;
				$table .= ' <tr>
                                            <td>'.$b.'</td>
                                            <td>'.$row['title'].'</td>
                                            <td>'.$row['level'].'</td>
                                            <td>$'.$row['award'].'</td>
                                            <td>'.$row['award2'].'</td>
                                            <td>'.$number.'</td>
                                            
                                            <td>'.$awarded.'</td>
                                            
                                             <td>'.$notawarded.'</td>
                                            
                                        </tr>';

                                    }
                                    $table .= ' </tbody></table>';
                                    return $table;
}




function levelRewards(){
	global $db;
	$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Stage</th>
                                             <th>Level</th>
                                             <th>Cash Reward</th>
                                           <th>Other Reward</th>
                                            <th>Action</th>
                                        
                                           </tr>
                                    </thead>
                                   
                                    <tbody>';
			$a = 1;
	$qu=$db->query("SELECT * FROM levels " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
				
					$b = $a++;
					
				$table .= ' <tr>
                                            <td>'.$b.'</td>
                                            <td>'.$row['title'].'</td>
                                            <td>'.$row['level'].'</td>
                                            <td><form method="post">
                                <input type="text" name="award" value="'.$row['award'].'"></td>
                                            <td>
                                <input type="text" name="award2" value="'.$row['award2'].'"></td>
                                           
                                            
                                             <td><button type="submit" name="updateAward" class="btn btn-success btn-xs" value="'.$row['sn'].'">Update Reward</button></form></td>
                                            
                                        </tr>';

                                    }
                                    $table .= ' </tbody></table>';
                                    return $table;
}


function updateAward(){
	global $db, $report, $count;
$sn = $_POST['updateAward'];
$reward = sanitize($_POST['award']);
$reward2 = sanitize($_POST['award2']);
$sql = $db->query("UPDATE levels SET award = '$reward', award2 = '$reward2' WHERE sn = '$sn' ");
if ($sql) {
	$report = 'Level Reward Successfully Updated!';
}else{$report = 'Level Reward Update not Successful!'; $count=1;}
	return;

}

function levelUsers($level){
	global $db;
			$count = 0;
	$qu=$db->query("SELECT * FROM user " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
			if($level==$this->wildLevel2($row['sn'])){$count += 1;}
			}
return $count;
}



function stageUsers($stage){
	global $db;
			$count = 0;
	$qu=$db->query("SELECT * FROM user WHERE st1=1" )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
			if($stage==$this->wildLevel2($row['sn'],2)){$count += 1;}
			}
return $count;
}


function allPins(){
	global $db;
			$count = 0;
	$qu=$db->query("SELECT * FROM pin " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
$count += 1;
			}
return $count;
}


function activePins(){
	global $db;
			$count = 0;
	$qu=$db->query("SELECT * FROM pin WHERE status=0 " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
$count += 1;
			}
return $count;
}




function sendMessage(){
	global $userKey, $report;
$message=addslashes($_POST['message']);
$subject=addslashes($_POST['subject']);

$this->message('Admin',$userKey,$message,$subject);
$report='Your message was successfully sent';
return;	
}

function sendMessageToAll(){
	global $report;
$message=addslashes($_POST['message']);
$subject=addslashes($_POST['subject']);

$this->message(1,'Admin',$message,$subject);
$report='Your message was successfully sent to all members';
return;	
}



function message($id,$sender,$msg,$subject){
global $db;
$ctime = CTIME;
$msg = $db->query("INSERT INTO msg (rec,sender,subject,msg,ctime)
VALUES('$id','$sender','$subject','$msg','$ctime')") or die(mysqli_error());

	return;
}

//administrator messages
function adminMsg($nu=''){
global $db,$userKey;
$msg = '';
$bl = ['info','warning','primary','danger','success'];
$a = 0;
$usercreated = $this->uName($userKey,'created');
$sql=$db->query("SELECT * FROM msg WHERE (rec = '$userKey' OR rec = 1 OR sender = '$userKey') AND created >= '$usercreated' ORDER BY sn DESC " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);
			while($row = mysqli_fetch_assoc($sql)){ $sn=$row['sn'];
				if($row['active']==1){$sql=$db->query("UPDATE msg SET active=2 WHERE sn = '$sn' " ); }
				$b=$a++;
				$c = $b%5; 
				if($row['sender']=='Admin'){ $sender='Admin';}else{$sender = ucwords($this->uName($row['sender']));}
				if($row['rec']==$userKey OR $row['rec']==1){$bb='bl';  $bg='';}else{$bb='br'; $bg='style="background-color:#FFFFCA"';}
$msg .= ' <li class="list-group-item '.$bb.'-'.$bl[$c].'" id="'.$row['subject'].'" '.$bg.'>
                                            
                                                    <span class="font-16"><strong>'.$sender.': '.$row['subject'].'</strong><br>'.htmlspecialchars($row['msg']).'</span>
                                               
                                                <h6 class="">'.date('d-M-y h:i A',$row['ctime']).$this->findReply($row['sn']).'</h6>
                                            
                                        </li>';
			}
			if($nu==1){$sql=$db->query("SELECT * FROM msg WHERE (rec = '$userKey' OR  rec = 1) AND created >= '$usercreated' " )or die(mysqli_error());
			$num = mysqli_num_rows($sql); $msg=$num;}
	return $msg;
}

function findReply($mid){
global $db;
$reply = '<br><b>Reply:</b> ';
$sq=$db->query("SELECT * FROM replymsg WHERE mid = '$mid' " )or die(mysqli_error());
while($ro = mysqli_fetch_assoc($sq)){ $reply .= '<li>'.htmlspecialchars($ro['reply']).'</li>'; }
$reply = (mysqli_num_rows($sq)>0) ? '<ul>'.$reply.'</li>' : '';
return $reply;
}

//administrator messages
function adminMsgAll(){
global $db;
$msg = '';
$bl = ['info','warning','primary','danger','success'];
$a = 0;
if(isset($_GET['reply'])){ $reply = $_GET['reply']; 
$sq=$db->query("SELECT * FROM msg WHERE sn = '$reply' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sq); $user = $ro['sender'];
$sql=$db->query("SELECT * FROM msg WHERE rec = '$user' OR  rec = '1' OR  sender = '$user' ORDER BY sn DESC " )or die(mysqli_error()); }
else{
$sql=$db->query("SELECT * FROM msg ORDER BY sn DESC LIMIT 200 " )or die(mysqli_error());  }
			$num = mysqli_num_rows($sql);
			while($row = mysqli_fetch_assoc($sql)){
				$user = ($row['sender'] == 'Admin') ? $row['rec'] : $row['sender'] ;
				$b=$a++;
				$c = $b%5; 
				if($row['sender']=='Admin'){ $sender='Admin';}else{$sender = ucwords($this->uName($row['sender']));}
				if($row['rec']=='1'){ $rec='All';}elseif($row['rec']=='Admin'){ $rec='Admin';}else{$rec = ucwords($this->uName($row['rec']));}
				if($row['rec']==$user){$bb='bl';  $bg='';}else{$bb='br'; $bg='style="background-color:#FFFFCA"';}
$msg .= ' <li class="list-group-item '.$bb.'-'.$bl[$c].'" id="'.$row['subject'].'" '.$bg.'>
                                            
                                                    <span class="font-16"><strong>['.$sender.' - '.$rec.'] '.$row['subject'].'</strong><br>'.htmlspecialchars($row['msg']).'</span>
                                               
                      <h6 class="">'.date('d-M-y h:i A',$row['ctime']).$this->findReply($row['sn']);
              if($sender != 'Admin'){$msg .= ' <a href="?reply='.$row['sn'].'"> Reply</a>'; }
              if(isset($_GET['reply'])){ if($_GET['reply']==$row['sn']){$msg .= '<br><form method="post"><input class="form-control" onchange="submit" name="replyMsg" placeholder="Enter reply & press enter" autofocus></form>';  } }
             $msg .=  '</h6>
                                            
                                        </li>';
			}
	return $msg;
}


//administrator messages
function adminMsgUser($user){
global $db;
$msg = '';
$bl = ['info','warning','primary','danger','success'];
$a = 0;
$sql=$db->query("SELECT * FROM msg WHERE rec = '$user' OR  rec = '1' OR  sender = '$user' ORDER BY sn DESC " )or die(mysqli_error());
			$num = mysqli_num_rows($sql);
			while($row = mysqli_fetch_assoc($sql)){
				$b=$a++;
				$c = $b%5; 
				if($row['sender']=='Admin'){ $sender='Admin';}else{$sender = ucwords($this->uName($row['sender']));}
				if($row['rec']=='1'){ $rec='All';}elseif($row['rec']=='Admin'){ $rec='Admin';}else{$rec = ucwords($this->uName($row['rec']));}
				if($row['rec']==$userKey){$bb='bl';  $bg='';}else{$bb='br'; $bg='style="background-color:#FFFFCA"';}
$msg .= ' <li class="list-group-item '.$bb.'-'.$bl[$c].'" id="'.$row['subject'].'" '.$bg.'>
                                            
                                                    <span class="font-16"><strong>['.$sender.' - '.$rec.'] '.$row['subject'].'</strong><br>'.htmlspecialchars($row['msg']).'</span>
                                               
                                                <h6 class="">'.date('d-M-y h:i A',$row['ctime']).' <a href="?reply='.$row['sn'].'"> Reply</a></h6>
                                            
                                        </li>';
			}
			if($nu==1){$sql=$db->query("SELECT * FROM msg WHERE rec = '$userKey' " )or die(mysqli_error());
			$num = mysqli_num_rows($sql); $msg=$num;}
	return $msg;
}



//administrator messages on top nav
function adminMsg2($nu=''){
global $db,$userKey;
$msg = '';
$bl = ['info','warning','primary','danger','success'];
$a = 0;
$usercreated = $this->uName($userKey,'created');
$sql=$db->query("SELECT * FROM msg WHERE (rec = '$userKey' OR rec = 1) AND active = 1 AND created >= '$usercreated' ORDER BY sn DESC" )or die(mysqli_error());
			$num = mysqli_num_rows($sql);
			while($row = mysqli_fetch_assoc($sql)){
				$b=$a++;
				$c = $b%5; 
$msg .= '<a href="messages.php#'.$row['subject'].'">
                                        
                                        <div class="mail-contnet">
                                            <h5>'.$row['subject'].'</h5>
                                            <span class="mail-desc">'.htmlspecialchars($row['msg']).'</span>
                                            <span class="time">'.date('d-M h:i A',$row['ctime']).'</span>
                                        </div>
                                    </a>';
			}
			if($nu==1){$msg=$num;}
	return $msg;
}

function paystackCharge($amt,$opt=''){
$result = 100 + ($amt*0.015); 
//$result = ($result<2500) ? $result-100 : $result;
$result = ($opt==1) ? $result+$amt : $result;
return $result;
}


function stgTost($stg){
	if($stg==1){$s = 'Waiting';}
	elseif($stg==2){$s = 'Induction';}
	elseif($stg==3){$s = 'Stage 1';}
	elseif($stg==4){$s = 'Stage 2';}
	elseif($stg==5){$s = 'Stage 3';}
	elseif($stg==6){$s = 'Stage 4';}
	elseif($stg==7){$s = 'Stage 5';}
return $s; 
}


function stgTostage($stg){
		if($stg==1){$s = 'Induction';}
	elseif($stg==2){$s = 'Stage 1';}
	elseif($stg==3){$s = 'Stage 2';}
	elseif($stg==4){$s = 'Stage 3';}
	elseif($stg==5){$s = 'Stage 4';}
	elseif($stg==6){$s = 'Stage 5';}
return $s; 
}



function stagetoLevel($stage,$level){
		if($stage==1 && $level==0){$lev = 1;}
	elseif($stage==1 && $level==1){$lev = 2;}
	elseif($stage==2 && $level==0){$lev = 3;}
	elseif($stage==2 && $level==1){$lev = 4;}
	elseif($stage==2 && $level==2){$lev = 5;}
	elseif($stage==3 && $level==0){$lev = 6;}
	elseif($stage==3 && $level==1){$lev = 7;}
	elseif($stage==3 && $level==2){$lev = 8;}
	elseif($stage==4 && $level==0){$lev = 9;}
	elseif($stage==4 && $level==1){$lev = 10;}
	elseif($stage==4 && $level==2){$lev = 11;}
	elseif($stage==5 && $level==0){$lev = 12;}
	elseif($stage==5 && $level==1){$lev = 13;}
	elseif($stage==5 && $level==2){$lev = 14;}
	  else{$lev=0;}
return $lev; 
}



function resetChart(){
unset($_SESSION['stg']);
header('location: ?');
	return;
}


function domTree($parent,$wing='a'){

	return 'a'.$wing.$parent.' = {
        parent: a'.$parent.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';
}

//$code .= 'a'.$left[1].', ' ;

function domCode($wing,$no=1){

	$code = 'a'.$wing.', ' ;

if ($no==2) {
	$code .= 'aa'.$wing.', ' ;
	$code .= 'ab'.$wing.', ' ;
}



if ($no==3) {
	$code .= 'aa'.$wing.', ' ;
	$code .= 'ab'.$wing.', ' ;
	$code .= 'aaa'.$wing.', ' ;
	$code .= 'aba'.$wing.', ' ;
	$code .= 'aab'.$wing.', ' ;
	$code .= 'abb'.$wing.', ' ;

}

return $code;
}



function domChild($parent,$wing,$no=1){

	$tree = 'a'.$wing.' = {
        parent: a'.$parent.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';

if ($no==2) {
	$tree .= 'aa'.$wing.' = {
        parent: a'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';

 	$tree .= 'ab'.$wing.' = {
        parent: a'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';
}



if ($no==3) {
	$tree .= 'aa'.$wing.' = {
        parent: a'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';

 	$tree .= 'ab'.$wing.' = {
        parent: a'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';
    //end of two
	$tree .= 'aaa'.$wing.' = {
        parent: aa'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';

 	$tree .= 'aba'.$wing.' = {
        parent: aa'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';


    	$tree .= 'aab'.$wing.' = {
        parent: ab'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';

 	$tree .= 'abb'.$wing.' = {
        parent: ab'.$wing.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';
}

return $tree;
}

function childTree($parent,$child,$cname){
global $img;


	return 'a'.$child.' = {
        parent: a'.$parent.',
        text:{
            name: "'.$cname.'",
            title: "",
            contact: "",
        },
        link: {
            href: "?u-ref='.sha1($child).'"
        },
    
        image: "../headshots/'.$img.'"
    }, ';
}

function childTreeAll($parent,$child,$cname){
global $mystage;


	return 'a'.$child.' = {
        parent: a'.$parent.',
        text:{
            name: "'.$cname.'",
            title: "",
            contact: "",
        },
        link: {
            href: "?u-ref='.sha1($child).'"
        },
    
        image: "../headshots/users.png"
    }, ';
}


function childTreex($parent,$child,$cname){
global $mystage;


	return 'a'.$child.' = {
        parent: a'.$parent.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
    
        image: "../headshots/use.png"
    }, ';
}



function gTreex($opt=''){
global $db,$key,$report,$count,$user,$randomKey;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$keys = $ro['sn'];
}
//$level = $this->wildLevel2($randomKey,2);


				$randomKey = isset($_GET['u-ref']) ? $keys : $this->userName('sn');
				$user=$randomKey;
				$gen1 = $this->wildGen($randomKey,1);
				//$randomKey = $this->userName('sn');
			

				
				

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
        nodeAlign: "BOTTOM",
        connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
        image: "../headshots/feeder.png"
    },';  

			
		if($gen1==0){	$code .= 'aa'.$randomKey.', ' ;
				$tree .= $this->domTree($randomKey);

    	$code .= 'ab'.$randomKey.', ' ;
				$tree .= $this->domTree($randomKey,'b');
}
elseif($gen1==1){

		$qu=$db->query("SELECT * FROM user WHERE a1 = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){

		$code .= 'a'.$row['sn'].', ' ;
				$tree .= $this->childTree($randomKey,$row['sn'],$row['user']);

			}

		$code .= 'aa'.$randomKey.', ' ;	
		$tree .= $this->domTree($randomKey);	
}
else{
	$qu=$db->query("SELECT * FROM user WHERE a1 = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){

		$code .= 'a'.$row['sn'].', ' ;
				$tree .= $this->childTree($randomKey,$row['sn'],$row['user']);

			}
}


			$code .='];';

			//$report = 'Showing your '.$this->stgTost($mystage).' geneology ';
			//$count = 0;
		return $tree.$code; 

			
			}



/*

function gTreey($opt=''){
global $db,$key,$report,$count,$user,$randomKey;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$keys = $ro['sn'];
}
//$level = $this->wildLevel2($randomKey,2);




				$randomKey = isset($_GET['u-ref']) ? $keys : $this->userName('sn');
				$user=$randomKey;
				$gen1 = $this->wildGen($randomKey,1);
				//$randomKey = $this->userName('sn');
				$leftkey = $this->wildLegKey($randomKey);
				$rightkey = $this->wildLegKey($randomKey,1);
			

				
				

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
        nodeAlign: "BOTTOM",
        connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
        image: "../headshots/induction.png"
    },';  

//left child
    if(isset($leftkey) && $this->wildSponsored($leftkey)>1){
    	$left = $this->wildLegKey($leftkey);
		$right = $this->wildLegKey($leftkey,1);
    	
 $code .= 'a'.$leftkey.', ' ;
 $tree .= $this->childTree($randomKey,$leftkey,$this->wildUserName($leftkey,'user'));  

//left grand child
  if(isset($left) && $this->wildSponsored($left)>1){
   $code .= 'a'.$left.', ' ;
 $tree .= $this->childTree($leftkey,$left,$this->wildUserName($left,'user'));   		
    	
    }else{
    	$code .= 'aa'.$leftkey.', ' ;
		$tree .= $this->domTree($leftkey);
    }
    //right grand child
   if(isset($right) && $this->wildSponsored($right)>1){
  $code .= 'a'.$right.', ' ;
 $tree .= $this->childTree($leftkey,$right,$this->wildUserName($right,'user'));   		
    	
    }else{
    	$code .= 'ab'.$leftkey.', ' ;
		$tree .= $this->domTree($leftkey,'b');
    } 		
    	
    }else{
    	$code .= 'aa'.$randomKey.', ' ;
		$tree .= $this->domTree($randomKey);

		$grand = 'a'.$randomKey;
		$code .= 'ae'.$grand.', ' ;
		$tree .= $this->domTree($grand,'e');

		$code .= 'af'.$grand.', ' ;
		$tree .= $this->domTree($grand,'f');
    }




//right child
        if(isset($rightkey) && $this->wildSponsored($rightkey)>1){
        $left = $this->wildLegKey($rightkey);
		$right = $this->wildLegKey($rightkey,1);

 $code .= 'a'.$rightkey.', ' ;
 $tree .= $this->childTree($randomKey,$rightkey,$this->wildUserName($rightkey,'user'));   		
    	
    	//left grand child
     if(isset($left) && $this->wildSponsored($left)>1){
   $code .= 'a'.$left.', ' ;
 $tree .= $this->childTree($rightkey,$left,$this->wildUserName($left,'user'));   		
    	
    }else{
    	$code .= 'aa'.$rightkey.', ' ;
		$tree .= $this->domTree($rightkey);
    }
    //right grand child
   if(isset($right) && $this->wildSponsored($right)>1){
  $code .= 'a'.$right.', ' ;
 $tree .= $this->childTree($rightkey,$right,$this->wildUserName($right,'user'));   		
    	
    }else{
    	$code .= 'ab'.$rightkey.', ' ;
		$tree .= $this->domTree($rightkey,'b');
    }
    }else{
    	$code .= 'ab'.$randomKey.', ' ;
		$tree .= $this->domTree($randomKey,'b');

		//'a'.$wing.$parent.' = {
      //  parent: a'.$parent.',
$grand = 'b'.$randomKey;
		$code .= 'ac'.$grand.', ' ;
		$tree .= $this->domTree($grand,'c');

		$code .= 'ad'.$grand.', ' ;
		$tree .= $this->domTree($grand,'d');
    }
    		



			$code .='];';

			//$report = 'Showing your '.$this->stgTost($mystage).' geneology ';
			//$count = 0;
		return $tree.$code; 

			
			}


*/







function gTreey($opt=''){
global $db,$key,$img,$user;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$keys = $ro['sn'];
$randomKey = $keys;
$left = explode(',',$this->legH($this->wildLegKey($keys)));
$right = explode(',',$this->legH($this->wildLegKey($keys,1)));
}else{
$randomKey = $this->userName('sn');
$left = explode(',',$this->legH($this->legKey()));
$right = explode(',',$this->legH($this->legKey(1)));
}

$user=$randomKey;
$img = 'induction.png';





				


				
				

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
         nodeAlign: "BOTTOM",
         connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
        image: "../headshots/induction.png"
    },';  

   if(!empty($left[0])){
 $code .= 'a'.$left[0].', ' ;
 $tree .= $this->childTree($randomKey,$left[0],$this->wildUserName($left[0],'user'));  
    }else{
    	//$code .= 'aa'.$randomKey.', ' ;
		//$tree .= $this->domTree($randomKey,'a');
		$code .= $this->domCode('x',2);
		$tree .= $this->domChild($randomKey,'x',2);
	}

   if(!empty($left[0])){
   	 if(!empty($left[1])){
 $code .= 'a'.$left[1].', ' ;
 $tree .= $this->childTree($left[0],$left[1],$this->wildUserName($left[1],'user'));  
    } else{
    	$code .= $this->domCode('y');
		$tree .= $this->domChild($left[0],'y');
	}

	   if(!empty($left[2])){
 $code .= 'a'.$left[2].', ' ;
 $tree .= $this->childTree($left[0],$left[2],$this->wildUserName($left[2],'user'));  
    } else{
    	$code .= $this->domCode('z');
		$tree .= $this->domChild($left[0],'z');
	}
}








   if(!empty($right[0])){
 $code .= 'a'.$right[0].', ' ;
 $tree .= $this->childTree($randomKey,$right[0],$this->wildUserName($right[0],'user'));  
    }else{
		$code .= $this->domCode('p',2);
		$tree .= $this->domChild($randomKey,'p',2);
	}

   if(!empty($right[0])){
   	if(!empty($right[1])){
 $code .= 'a'.$right[1].', ' ;
 $tree .= $this->childTree($right[0],$right[1],$this->wildUserName($right[1],'user'));  
    } else{
    	$code .= $this->domCode('q');
		$tree .= $this->domChild($right[0],'q');
	}

	   if(!empty($right[2])){
 $code .= 'a'.$right[2].', ' ;
 $tree .= $this->childTree($right[0],$right[2],$this->wildUserName($right[2],'user'));  
    } else{
    	$code .= $this->domCode('r');
		$tree .= $this->domChild($right[0],'r');
	}
}


			$code .='];';

			//$report = 'Showing your '.$this->stgTost($mystage).' geneology ';
			//$count = 0;
		return $tree.$code; 

			
			}






function gTreez($st=3){
global $db,$img,$user;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$keys = $ro['sn'];
$randomKey = $keys;
//legSt($key,$st)
$left = explode(',',$this->legSt($this->wildLegKey($keys),$st));
$right = explode(',',$this->legSt($this->wildLegKey($keys,1),$st));
}else{
$randomKey = $this->userName('sn');
$left = explode(',',$this->legSt($this->legKey(),$st));
$right = explode(',',$this->legSt($this->legKey(1),$st));
}

$user=$randomKey;
$img = $this->image2($st);



				


				
				

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
         nodeAlign: "BOTTOM",
         connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
        image: "../headshots/'.$img.'"
    },';  

   if(!empty($left[0])){
 $code .= 'a'.$left[0].', ' ;
 $tree .= $this->childTree($randomKey,$left[0],$this->wildUserName($left[0],'user'));  
    }else{
    	//$code .= 'aa'.$randomKey.', ' ;
		//$tree .= $this->domTree($randomKey,'a');
		$code .= $this->domCode('x',3);
		$tree .= $this->domChild($randomKey,'x',3);
	}

   if(!empty($left[0])){
   	 if(!empty($left[1])){
 $code .= 'a'.$left[1].', ' ;
 $tree .= $this->childTree($left[0],$left[1],$this->wildUserName($left[1],'user'));  
    } else{
    	$code .= $this->domCode('y',2);
		$tree .= $this->domChild($left[0],'y',2);
	}

	   if(!empty($left[2])){
 $code .= 'a'.$left[2].', ' ;
 $tree .= $this->childTree($left[0],$left[2],$this->wildUserName($left[2],'user'));  
    } else{
    	$code .= $this->domCode('z',2);
		$tree .= $this->domChild($left[0],'z',2);
	}
}





   if(!empty($left[1])){
   	if(!empty($left[3])){
 $code .= 'a'.$left[3].', ' ;
 $tree .= $this->childTree($left[1],$left[3],$this->wildUserName($left[3],'user'));  
    } else{
$code .= $this->domCode('l');
$tree .= $this->domChild($left[1],'l');
	}

	   if(!empty($left[4])){
 $code .= 'a'.$left[4].', ' ;
 $tree .= $this->childTree($left[1],$left[4],$this->wildUserName($left[4],'user'));  
    } else{
$code .= $this->domCode('m');
$tree .= $this->domChild($left[1],'m');
	}
}






   if(!empty($left[2])){
   	if(!empty($left[5])){
 $code .= 'a'.$left[5].', ' ;
 $tree .= $this->childTree($left[2],$left[5],$this->wildUserName($left[5],'user'));  
    } else{
$code .= $this->domCode('n');
$tree .= $this->domChild($left[2],'n');
	}

	   if(!empty($left[6])){
 $code .= 'a'.$left[6].', ' ;
 $tree .= $this->childTree($left[2],$left[6],$this->wildUserName($left[6],'user'));  
    } else{
$code .= $this->domCode('o');
$tree .= $this->domChild($left[2],'o');
	}
}




   if(!empty($right[0])){
 $code .= 'a'.$right[0].', ' ;
 $tree .= $this->childTree($randomKey,$right[0],$this->wildUserName($right[0],'user'));  
    }else{
		$code .= $this->domCode('p',3);
		$tree .= $this->domChild($randomKey,'p',3);
	}

   if(!empty($right[0])){
   	if(!empty($right[1])){
 $code .= 'a'.$right[1].', ' ;
 $tree .= $this->childTree($right[0],$right[1],$this->wildUserName($right[1],'user'));  
    } else{
    	$code .= $this->domCode('q',2);
		$tree .= $this->domChild($right[0],'q',2);
	}

	   if(!empty($right[2])){
 $code .= 'a'.$right[2].', ' ;
 $tree .= $this->childTree($right[0],$right[2],$this->wildUserName($right[2],'user'));  
    } else{
    	$code .= $this->domCode('r',2);
		$tree .= $this->domChild($right[0],'r',2);
	}
}





   if(!empty($right[1])){
   	if(!empty($right[3])){
 $code .= 'a'.$right[3].', ' ;
 $tree .= $this->childTree($right[1],$right[3],$this->wildUserName($right[3],'user'));  
    } else{
    	$code .= $this->domCode('s');
		$tree .= $this->domChild($right[1],'s');
	}

	   if(!empty($right[4])){
 $code .= 'a'.$right[4].', ' ;
 $tree .= $this->childTree($right[1],$right[4],$this->wildUserName($right[4],'user'));  
    } else{
    $code .= $this->domCode('t');
	$tree .= $this->domChild($right[1],'t');
	}
}





 if(!empty($right[2])){
   if(!empty($right[5])){
 $code .= 'a'.$right[5].', ' ;
 $tree .= $this->childTree($right[2],$right[5],$this->wildUserName($right[5],'user'));  
    } else{
$code .= $this->domCode('u');
$tree .= $this->domChild($right[2],'u');
	}

	   if(!empty($right[6])){
 $code .= 'a'.$right[6].', ' ;
 $tree .= $this->childTree($right[2],$right[6],$this->wildUserName($right[6],'user'));  
    } else{
$code .= $this->domCode('v');
$tree .= $this->domChild($right[2],'v');
	}
}





			$code .='];';

			//$report = 'Showing your '.$this->stgTost($mystage).' geneology ';
			//$count = 0;
		return $tree.$code; 

			
			}







function allTree($opt=''){
global $db,$key,$report,$count,$user,$randomKey,$mystage;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$keys = $ro['sn'];
}
//$level = $this->wildLevel2($randomKey,2);




				$randomKey = isset($_GET['u-ref']) ? $keys : $this->userName('sn');
				$user=$randomKey;
			
			$mystage = 0;
		
			

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
        nodeAlign: "BOTTOM",
        connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },
        image: "../headshots/users.png"
    },';  

$a = 1; $x = 1; $nu = 0;
			while($a<=3){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
			$child = $row['sn']; 
			$parent = $row['a1'];
		//	$stage = $this->wildLevel2($child,2);
			$y=$x++;
			  
			
			//$x = ($b==1) ? 'a' : 'b';
//left child
   
    	if($b<3){
 $code .= 'a'.$child.', ' ;
 $tree .= $this->childTreeAll($parent,$child,$this->wildUserName($child,'user'));

if($this->wildGen($child,1)==0){
		$code .= 'aa'.$child.', ' ;
		$tree .= $this->domTree($child,'a');

		$code .= 'ab'.$child.', ' ;
		$tree .= $this->domTree($child,'b');

}elseif($this->wildGen($child,1)==1){
		$code .= 'aa'.$child.', ' ;
		$tree .= $this->domTree($child,'a'); }
    	}else{
 $code .= 'a'.$child.', ' ;
 $tree .= $this->childTreeAll($parent,$child,$this->wildUserName($child,'user'));  
    }

  }

}



			$code .='];';

			//$report = 'Showing your '.$this->stgTost($mystage).' geneology ';
			//$count = 0;
		return $tree.$code; 

			
			}





function legStageProgress($leg=0){
	global $db;
$percent = 0;
	$randomKey = $this->legKey($leg);
	$upstage = $this->wildLevel2($this->userName('sn'),2);
	$mystage = $this->wildLevel2($randomKey,2);
		if($mystage==1){$show = 1;}elseif($mystage==2){$show = 2;}else{$show = 3;}
	$a = 1;  $nu = 0;
			while($a<=$show){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
			//$user = $row['sn'];
			$stage = $this->wildLevel2($row['sn'],2);
			//Indicate waiting user with < 2 sponsored
			if(($stage>=$upstage AND $this->wildSponsored($row['sn'])>1) OR ($show==1 AND $this->wildSponsored($randomKey)>1)){
				$nu += 1;
}} }
if($mystage>=$upstage){ $nu=$nu+1;
	if($upstage==1){$percent = 100*$nu/2;}elseif($upstage==2){$percent = 100*$nu/6;}else{$percent = 100*$nu/14;}
	}
	return number_format($percent,1).'%';
}


function levelProgress(){
global $db;
$key = $this->userName('sn');
	$level = $this->findLevel($key);
	$nextlevel = $level+1;
	$stagelevel = $this->wildLevel2($key,5)+1;
	$gen = 'a'.$stagelevel; 
	$target = 2**$stagelevel; 
	$upstage = $this->wildLevel2($key,2);
	$nu = 0;
	$qu=$db->query("SELECT * FROM user WHERE $gen = '$key' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
				$stage = $this->wildLevel2($row['sn'],2);
if(($stage>=$upstage AND $this->wildSponsored($row['sn'])>1) OR $level==0){
				$nu += 1;
}
}
$percent = (100*$nu/$target);
	
	return number_format($percent,1).'%';
}



function image($key){
$level = $this->wildLevel2($key,2);
	//if($this->wildSponsored($key)<2){ $wait = 'waiting.jpg' ;}
			if($level==1){ $wait = 'feeder.png' ;}
			elseif($level==2){ $wait = 'induction.png' ;}
			elseif($level==3){ $wait = 'stage1.png' ;}
			elseif($level==4){ $wait = 'stage2.png' ;}
			elseif($level==5){ $wait = 'stage3.png' ;}
			elseif($level==6){ $wait = 'stage4.png' ;}
			elseif($level==7){ $wait = 'stage5.png' ;}
			//elseif($level<1){ $wait = 'user4.jpg' ;}
			else{ $wait = 'stage5.png' ;}
			return $wait;
}

function image2($level){

			if($level==1){ $wait = 'feeder.png' ;}
			elseif($level==2){ $wait = 'induction.png' ;}
			elseif($level==3){ $wait = 'stage1.png' ;}
			elseif($level==4){ $wait = 'stage2.png' ;}
			elseif($level==5){ $wait = 'stage3.png' ;}
			elseif($level==6){ $wait = 'stage4.png' ;}
			elseif($level==7){ $wait = 'stage5.png' ;}
			//elseif($level<1){ $wait = 'user4.jpg' ;}
			else{ $wait = 'stage5.png' ;}
			return $wait;
}

//Geneology Tree
function gTreeAll(){
global $db,$key,$user;
$show = 3;
if(isset($_GET['u-ref'])){ $random = $_GET['u-ref'];
$sql=$db->query("SELECT * FROM user WHERE sha1(sn) = '$random' " )or die(mysqli_error());
$ro = mysqli_fetch_assoc($sql);
$key = $ro['sn'];
}
				$randomKey = isset($_GET['u-ref']) ? $key : $this->userName('sn');
				$mystage = $this->wildLevel2($randomKey,2);
				$sstag = $this->Level(1);
				$user = $randomKey;

				$code='chart_config = [
        config, a'.$randomKey.', ';

				$tree='var config = {
        container: "#basic-example",
        nodeAlign: "BOTTOM",
        connectors: {
            type: "step"
        },
        node: {
            HTMLclass: "nodeExample1"
        }
    },';
				$tree.='a'.$randomKey.' = {
        text: {
            name: "'.$this->userNameWild('user').'",
            title: "",
            contact: "",
        },
        link: {
            href: ""
        },

        image: "../headshots/users.png"
    },';  

if($this->wildGen($randomKey,1)==0){ 
				$code .= 'aa'.$randomKey.', ' ;
				$tree .= 'aa'.$randomKey.' = {
        parent: a'.$randomKey.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$this->userNameWild('user').'"
        },
    
        image: "../headshots/reg.png"
    }, ';

    	$code .= 'ab'.$randomKey.', ' ;
				$tree .= 'ab'.$randomKey.' = {
        parent: a'.$randomKey.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$this->userNameWild('user').'"
        },
    
        image: "../headshots/reg.png"
    }, ';
     }





//   contact: "'.$this->wildLevel2($randomKey,7).'",
			$a = 1; $x = 1; $c=0; $nu = 0;
			while($a<=$show){$b = $a++; $gen = 'a'.$b; 
			$qu=$db->query("SELECT * FROM user WHERE $gen = '$randomKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($qu)){
			$user = $row['sn'];

			
			$code .= 'a'.$row['sn'].', ' ;
				$tree .= 'a'.$row['sn'].' = {
        parent: a'.$row['a1'].',
        text:{
            name: "'.$row['user'].'",
            title: "",
            contact: "",
        },
        link: {
            href: "?u-ref='.sha1($row['sn']).'"
        },
    
        image: "../headshots/users.png"
    }, ';


     if($this->wildGen($randomKey,1)==1 && $b==1){ 
				$code .= 'aa'.$randomKey.', ' ;
				$tree .= 'aa'.$randomKey.' = {
        parent: a'.$randomKey.',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$this->userNameWild('user').'"
        },
    
        image: "../headshots/reg.png"
    }, ';
    }

		if($this->wildGen($row['sn'],1)==0 && $b<3){ 
				$code .= 'aa'.$row['sn'].', ' ;
				$tree .= 'aa'.$row['sn'].' = {
        parent: a'.$row['sn'].',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$row['user'].'"
        },
    
        image: "../headshots/reg.png"
    }, ';

    	$code .= 'ab'.$row['sn'].', ' ;
				$tree .= 'ab'.$row['sn'].' = {
        parent: a'.$row['sn'].',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$row['user'].'"
        },
    
        image: "../headshots/reg.png"
    }, ';
     }
      
    if($this->wildGen($row['a1'],1)==1 && $b<4){ 
    	$user = $row['a1'];
				$code .= 'aa'.$row['a1'].', ' ;
				$tree .= 'aa'.$row['a1'].' = {
        parent: a'.$row['a1'].',
        text:{
            name: "",
            title: "",
            contact: "",
        },
        link: {
            href: "registernew.php?reff='.$this->userNameWild('user').'"
        },
    
        image: "../headshots/reg.png"
    }, ';
    } 
    

				}
			}	
			//contact: "'.$this->wildLevel2($row['sn'],7).'",
			$code .='];';
			
			return $tree.$code;
			}





function stageEarning($opt=''){
$stage = 2**$this->Level();
$total = 0;
$a=1;
while($a<=$this->Level()){$b=$a++;
$total += 2**$b;
}
if($opt==1){return 1.5*$total;}else{return 1.5*$stage;}
}
	//user Rank		
			
	function Rank($user){
			if($this->Downlines()<3){$rank = 0;}elseif($this->Downlines()<12){$rank = 1;}elseif($this->Downlines()<39){$rank = 2;}elseif($this->Downlines()<120){$rank = 3;}elseif($this->Downlines()<363){$rank = 4;}elseif($this->Downlines()<1092){$rank = 5;}elseif($this->Downlines()<3279){$rank = 6;}elseif($this->Downlines()<9840){$rank = 7;}elseif($this->Downlines()<29523){$rank = 8;}elseif($this->Downlines()<88572){$rank = 9;}else{$rank = 10;}
	return $rank;
	}
	
	//Bonus Types
	function matrixB(){
		global $id;
	return $this->Downlines()*$this->percent()/$this->dola;	
	}
	
	function referalB(){
		return $this->Sponsored()*2;	
	}
	

	function percent($p=5){
	return	$this->amount*$p/100;
	}

	//Withdrawal Methods



function confirmedWithdraw(){
	global $db,$userKey;
	
	$status = STATUSALPHA;
	
	$sql = $db->query("SELECT amount FROM withdraw WHERE id2 = '$userKey' AND status = '$status' ");
	$amt = 0;
	while($row = mysqli_fetch_assoc($sql)){
		$amt += $row['amount'];
	}
	return $amt; 
}





function userWithdraw(){
	
	return $this->confirmedWithdraw()+$this->pendingWithdraw(); 
}


function pendingWithdraw(){
global $db,$userKey;

	$status = STATUSBETA;
	
	$sql = $db->query("SELECT amount FROM withdraw WHERE id2 = '$userKey' AND status = '$status' ");
	$amt = 0;
	while($row = mysqli_fetch_assoc($sql)){
		$amt += $row['amount'];
	}
	return $amt; 
}

function accountBalance(){
	return $this->totalEarning()-$this->confirmedWithdraw()-$this->pendingWithdraw();
}


	function possibleEpin(){
		return (int)($this->accountBalance()/$this->dolafee);
	}


//Withdrawal Order
	function buyEpins(){
		global $epinqty,$paytype,$report,$count;
	$epinqty = sanitize($_POST['pins']);
	$withdrawAmount = $epinqty*$this->dolafee;
	$approval = md5($_POST['approval']);
	$type = 'E-PIN Purchase';
	$status = 1;
			$accountBalance = $this->Balance();
			$finalbalance = $accountBalance-$withdrawAmount;
		
	
if($this->userName('pass')==$approval && $withdrawAmount<=$accountBalance && $withdrawAmount>=$this->minwithdraw ){
	$this->withdrawProcess($withdrawAmount,$type,$status);
	$this->sellEpins($epinqty,'Wallet Pay');
	$report = 'Transaction Successful';
}else{
	$report = 'Transaction Unsuccessful. Authentication failed or insufficient balance'; $count =1;
}

return;
}



function confirmPinPayment(){
	global $db;
	$payref = $_GET['tr_referenca'];
	$epinqty = $_SESSION['pins'];

	if($_GET['tr_referenca']==$_SESSION['referenca']){
		$this->sellEpins($epinqty,'Card Pay');
	$_SESSION['report']='Payment Successful. Your newly purchases E-PINs ('.$epinqty.') have been delivered to you';
	}
	unset($_SESSION['referenca']);
	header("location: ?payment-confirmed=online");
	return;
}


//Withdrawal Order
	function approvePinRequest(){
		global $db,$epinqty,$paytype,$report,$count;
	$epinqty = sanitize($_POST['pins']);
	$sn = $_POST['approvePinRequest'];
	//$withdrawAmount = $epinqty*10;//$this->$dolafee;
	$approval = md5($_POST['approval']);
	$type = 'E-PIN Request';
	$status = 1;

	$sq = $db->query("SELECT * FROM payment WHERE sn = '$sn' ");
	$row = mysqli_fetch_assoc($sq);
	$key = $row['id'];
			//$accountBalance = $this->accountBalance();
			//$finalbalance = $accountBalance-$withdrawAmount;
		
	
if($this->userName('pass')==$approval){
	//$this->withdrawProcess($withdrawAmount,$type,$status);
	$sql = $db->query("UPDATE payment SET status=1, buy='$epinqty' WHERE sn = '$sn' ");
	$this->sellEpinsAdmin($epinqty,$key);
	$report = 'Transaction Successful';
}else{
	$report = 'Transaction Unsuccessful. Authentication failed or insufficient balance'; $count =1;
}

return;
}



//Withdrawal Order
	function deletePinRequest(){
		global $db,$epinqty,$paytype,$report,$count;
	
	$sn = $_POST['deletePinRequest'];
	$approval = md5($_POST['approval']);
		
if($this->userName('pass')==$approval){
$sq = $db->query("DELETE FROM payment WHERE sn = '$sn' ");
	$report = 'Successfully Deleted Pin Request';
}else{
	$report = 'Transaction Unsuccessful. Authentication failed'; $count =1;
}


return;
}



//Withdrawal Order
	function requestEpins(){
		global $db,$userKey,$report,$count,$signup;
	$epinqty = sanitize($_POST['pins']);
	$details = sanitize($_POST['details']);

	$approval = md5($_POST['approval']);
	$type = 'E-PIN Request';

	$doc = $signup->win_hashs(5).str_replace(" ", "-", $_FILES['docc']['name']);
	define('upload', 'payment/');
	if(isset($doc) AND strlen($doc)>4){
	$success = move_uploaded_file($_FILES['docc']['tmp_name'], upload.$doc);  
}
	
if($this->userName('pass')==$approval){
$msg = $db->query("INSERT INTO payment (id,qty,details,type,image)
VALUES('$userKey','$epinqty','$details','$type','$doc')") or die(mysqli_error());

	$report = 'Transaction Request Sent';
}else{
	$report = 'Transaction Request Not Sent. Authentication failed or insufficient balance'; $count =1;
}

return;
}





function sellEpins($epinqty,$type='Admin Auto'){
global $db, $userKey;
    $i=1;
    while($i<=$epinqty){
        $e=$i++;
$pin = substr(str_shuffle(str_repeat('123456789',10)),0,10);

$db->query("INSERT INTO pin (pin,rep,tm) VALUES('$pin','$userKey','$type')");


    }

    $msg = 'Pin purchase successful. The E-PINs you purchased ('.$epinqty.') have been delivered to you. click on BUY & MANAGE E-PINs from the menu to see the PINs';
$this->message($userKey,'Admin',$msg,'E-PIN Purchase');

	return;
}



function sellEpinsAdmin($epinqty,$key){
global $db;
    $i=1;
    while($i<=$epinqty){
        $e=$i++;
$pin = substr(str_shuffle(str_repeat('1234567890',10)),0,10);

$db->query("INSERT INTO pin (pin,rep,tm) VALUES('$pin','$key','Request')");
    }
$msg = 'Pin purchase successful. The E-PINs you purchased ('.$epinqty.') have been delivered to you. click on BUY & MANAGE E-PINs from the menu to see the PINs';
$this->message($key,'Admin',$msg,'E-PIN Purchase');
	return;
}




	function withdrawOrder(){
		global $report,$count;
		$withdrawAmount = sanitize($_POST['withdrawAmount']);
		$currentpass = md5($_POST['currentpass']);
		$withdrawAmount = $withdrawAmount + $this->withdrawcharge;

$type = 'Cash Withdrawal'; 

		$status = 0;
		if($currentpass == $this->userName('pass') AND $withdrawAmount <= $this->Balance()){
$this->withdrawProcess($withdrawAmount,$type,$status); 
}
else{$report = 'Password confirmation failed or invalid amount, please try again'; $count = 1;}
return;
}


	function transferOrder(){
		global $db,$report,$count,$userKey;
		$withdrawAmount = sanitize($_POST['withdrawAmount']);
		$recKey = sanitize($_POST['reckey']);
		$currentpass = md5($_POST['currentpass']);
		
		if($withdrawAmount<2 OR $withdrawAmount>4 OR $withdrawAmount>$this->Balance()){$report = 'You have entered an invalid amount'; $count = 1;}else{
$tno = substr(str_shuffle(str_repeat('1234567890',10)),0,10);

		if($currentpass == $this->userName('pass')){
$sql = $db->query("INSERT INTO transfer (id,id2,amount,tno) VALUES ('$userKey','$recKey','$withdrawAmount','$tno')");

if($sql){ $report='Your transfer has been successfully completed'; 
unset($_SESSION['recKey']); }
}
else{$report = 'Password confirmation failed, please try again'; $count = 1;}
}
return;
}



function courseOrder(){
		global $db,$report,$count,$userKey;		

		$course = $_POST['course'];
		$currentpass = md5($_POST['currentpass']);
		
$tno = substr(str_shuffle(str_repeat('1234567890',10)),0,10);

		if($currentpass == $this->userName('pass')){
$sql = $db->query("INSERT INTO download (id,course,tno) VALUES ('$userKey','$course','$tno')");

if($sql){ $report='Your preferred course has been successfully submited'; }
}
else{$report = 'Password confirmation failed, please try again'; $count = 1;}
return;
}








	function findCourse(){
		global $db,$userKey;
$sql=$db->query("SELECT * FROM download WHERE id='$userKey' " )or die(mysqli_error());
$find = (mysqli_num_rows($sql)>0) ? TRUE : FALSE ;

return $find;
}





			function withdrawProcess($withdrawAmount,$type,$status){
		global $db, $userKey,$report,$count;
		$tno = substr(str_shuffle(str_repeat('1234567890',10)),0,10);


		$accountBalance = $this->Balance();
			$finalbalance = $accountBalance-$withdrawAmount;
$sql = $db->query("INSERT INTO withdraw (id,inibalance,amount,finalbalance,status,type,tno) VALUES ('$userKey','$accountBalance','$withdrawAmount','$finalbalance','$status','$type','$tno')");

if($sql){ $report='Your withdrawal request has been successfully submitted'; $this->logdraw($tno); }

return;
	}





function logdraw($tno){
	global $db;
$sql = $db->query("INSERT INTO logdraw SELECT * FROM withdraw WHERE tno = '$tno' ");
return;
}


function withdrawHistory(){
			global $db,$userKey;

			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Transaction No</th>
                                            <th>Amount</th>
                                            <th>Charges</th>
                                            <th>Date</th>

                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
$i=1;
			$sql=$db->query("SELECT * FROM withdraw WHERE id = '$userKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){ $e=$i++; $status = ($row['status']==1)?'Complete':'Pending'; 
			$amt = ($row['type']=='Cash Withdrawal') ? '$'.($row['amount']-0.5) : '$'.$row['amount'];
			$charge = ($row['type']=='Cash Withdrawal') ? '$'.'0.5' : 0;
			
				$table .= ' <tr>
                                            <td>'.$e.'</td>
                                            <td>'.$row['tno'].'</td>
                                            <td>'.$amt.'</td>
                                            <td>'.$charge.'</td>
                                            <td>'.$row['created'].'</td>
                                            <td>'.$status.'</td>
                                             
                                        </tr>';
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}


function transferHistory(){
			global $db,$userKey;

			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Transaction No</th>
                                            <th>Amount</th>
                                            <th>Type</th>
                                            <th>Description</th>
                                            <th>From</th>
                                            <th>To</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
$i=1;   $amt = 0;
			$sql=$db->query("SELECT * FROM transfer WHERE id = '$userKey' OR id2 = '$userKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){ $e=$i++; 
			$amt += ($row['id']==$userKey) ? $row['amount'] : 0;
			$type = ($row['id']==$userKey) ? 'Debit' : 'Credit';
			$des = ($row['id']==$userKey) ? 'Transfer to '.$this->uName($row['id2']):'Received from '.$this->uName($row['id']);
			//$sender = ($row['id']==$userKey) ? $this->uName($row['id2']) : $this->uName($row['id']);
			
				$table .= ' <tr>
                                            <td>'.$e.'</td>
                                            <td>'.$row['tno'].'</td>
                                            <td>$'.$row['amount'].'</td>
                                          
                                            <td>'.$type.'</td>
                                            <td>'.$des.'</td>
                                             <td>'.$this->uName($row['id']).'</td>
                                              <td>'.$this->uName($row['id2']).'</td>
                                            <td>'.$row['created'].'</td>
                                             
                                        </tr>';
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}


/*
function fileDownload(){
			global $db,$userKey;

			$table = '<table  class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Code</th>
                                             <th>Course</th>
                                            <th>File</th>
                                            <th>Date</th>
                                             <th>Download</th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
$i=1;   $amt = 0;
			$sql=$db->query("SELECT * FROM download WHERE id = '$userKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){ $e=$i++; 
			$amt += ($row['id']==$userKey) ? $row['amount'] : 0;
			$type = ($row['id']==$userKey) ? 'Debit' : 'Credit';
			
			
				$table .= ' <tr>
                                            <td>'.$e.'</td>
                                            <td>'.$row['tno'].'</td>
                                            <td></td>
                                          
                                            <td>my-course-material.pdf</td>
                                             <td>'.$row['created'].'</td>
                                             
                                            <td><button onclick="document.getElementById('link').click()">Download Now!</button>
<a id="link" href="treant/opt'.$row['course'].'.pdf" download="my-course-material.pdf" hidden></a></td>
                                             
                                        </tr>';
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}
*/

function transferHistoryAdmin(){
			global $db,$userKey;

			$table = '<table id="example23" class="display nowrap" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th>SN</th>
                                             <th>Transaction No</th>
                                            <th>Amount</th>
                                            <th>Type</th>
                                            <th>From</th>
                                            <th>To</th>
                                            <th>Date</th>
                                        </tr>
                                    </thead>
                                   
                                    <tbody>';
$i=1;   $amt = 0;
if(isset($_GET['quser'])){$quser = $this->uNameUser($_GET['quser'],'id'); 
$sql=$db->query("SELECT * FROM transfer WHERE id = '$quser' OR id2 = '$quser' ORDER BY sn DESC  " )or die(mysqli_error()); }else{
			$sql=$db->query("SELECT * FROM transfer ORDER BY sn DESC LIMIT 100 " )or die(mysqli_error());
			}
			while($row = mysqli_fetch_assoc($sql)){ $e=$i++; 
			$amt += ($row['id']==$userKey) ? $row['amount'] : 0;
			$type = ($row['id']==$userKey) ? 'Debit' : 'Credit';
			//$sender = ($row['id']==$userKey) ? $this->uName($row['id2']) : $this->uName($row['id']);
			
				$table .= ' <tr>
                                            <td>'.$e.'</td>
                                            <td>'.$row['tno'].'</td>
                                            <td>$'.$row['amount'].'</td>
                                          
                                            <td>'.$type.'</td>
                                             <td><a href="?quser='.$this->uName($row['id']).'">'.$this->uName($row['id']).'</a></td>
                                              <td><a href="?quser='.$this->uName($row['id2']).'">'.$this->uName($row['id2']).'</a></td>
                                            <td>'.$row['created'].'</td>
                                             
                                        </tr>';
			}

			$table .= ' </tbody>
                                </table>';	
			return $table;	
			}




function transfered($opt=1){
global $db,$userKey;
$amt=0; $amt2=0;
$sql=$db->query("SELECT * FROM transfer WHERE id = '$userKey' OR id2 = '$userKey' " )or die(mysqli_error());
			while($row = mysqli_fetch_assoc($sql)){ 
			$amt += ($row['id']==$userKey) ? $row['amount'] : 0;
			$amt2 += ($row['id2']==$userKey) ? $row['amount'] : 0;
		}
$sum = ($opt==1) ? $amt : $amt2; 
return $sum;
}


function invTotalInt(){
	global $db,$userKey ;
	$status = STATUSALPHA;
	$amt=0;
	$sql = $db->query("SELECT * FROM invacc WHERE userid='$userKey' AND status='$status' ");
 while($row = mysqli_fetch_assoc($sql)){

$age = $this->accAge($row['accno'],1);
$interest = $age*$row['roi'];

 	$amt = $amt+$interest;
 }
	return $amt;
}


//from investment//
function accAge($accountno,$type=''){
	global $db,$userKey;
 $sql = $db->query("SELECT * FROM invacc WHERE accno='$accountno' ");
 $row = mysqli_fetch_assoc($sql);
 if($row['tan']>0){
 	$diff = CTIME-$row['tan'];
 $age = $diff/(86400);
$weeks = (int)($age/7);
if($age<=280){$percent = number_format((100*$age/280),1).'%';}

 if($type==1){return $weeks; }elseif($diff<3600){}elseif($diff>3600 && $age<1){ return (int)($diff/3600).' hours';} elseif($age<7){return (int)$age.' days<br>'.$percent;}elseif($age>7){return (int)($age/7).' weeks<br>'.$percent;} 
 //elseif($age>=30){return (int)($age/30).' months<br>'.$percent;}
 

 else{return; }
}


}


function approveWithdrawOrder(){
	global $db,$report,$count;
	$tno = $_POST['approveWithdrawOrder'];
	$currentpass = md5($_POST['currentpass']);

	$status = 1; 
if($this->userName('pass')==$currentpass){
$sql = $db->query("UPDATE logdraw SET status = '$status' WHERE tno = '$tno' ");
$sql = $db->query("UPDATE withdraw SET status = '$status' WHERE tno = '$tno' ");
if($sql){
	$report = 'Withdrawal order successfully approved';
}else{$report = 'Withdrawal approved not successful'; $count=1; }
}
else{
$report = 'Password confirmation failed, please try again'; $count = 1;	
}

return;
}


function approveIncentiveOrder(){
	global $db,$report,$count;
	$tno = $_POST['approveIncentiveOrder'];
	$currentpass = md5($_POST['currentpass']);

	$status = 1; 
if($this->userName('pass')==$currentpass){
$sql = $db->query("UPDATE award SET remark = '$status' WHERE sn = '$tno' ");
if($sql){
	$report = 'Withdrawal order successfully approved';
}else{$report = 'Withdrawal approved not successful'; $count=1; }
}
else{
$report = 'Password confirmation failed, please try again'; $count = 1;	
}

return;
}


function adminLevel(){

	if($this->userName('userlevel')==(strlen($this->userName('email'))*2) OR $this->userName('sn')==1){
		return TRUE;
	}else{return FALSE;}
}
	



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

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



function userProfileData($a){
	global $db;
	$id = $_SESSION['user_id'];
	$sql=$db->query("SELECT * FROM user WHERE id = '$id' " )or die(mysqli_error()); 
$row=mysqli_fetch_assoc($sql);

$data = '                        <div class="col-md-4 col-xs-12">
                        <div class="white-box">
                            <div class="user-bg"> <img width="100%" alt="user" src="photo/'.$row['photo'].'">
                                <div class="overlay-box">
                                    <div class="user-content">
                                        <a href="javascript:void(0)"><img src="photo/'.$row['photo'].'" class="thumb-lg img-circle" alt="img"></a>
                                        <h4 class="text-white">'.$row['firstname'].' '.$row['lastname'].'</h4>
                                        <h5 class="text-white">'.$row['email'].'</h5> </div>
                                </div>
                            </div>

                             <hr>
                               
                                <!-- .row -->
                                <div class="row text-center m-t-10">
                                    <div class="col-md-6 col-xs-6 b-r"><strong>Sponsor</strong>
                                        <p>'.$this->wildUserName($row['sponsor']).'</p>
                                    </div>
                                    <div class="col-md-6 col-xs-6"><strong>Upline</strong>
                                        <p>'.$this->wildUserName($row['a1']).'</p>
                                    </div>
                                </div>
                                <!-- /.row -->

                            

                            
                        </div>
                    </div>';



               



                    $data2 = '<div class="col-md-8 col-xs-12">
                        <div class="white-box">
                            <!-- .tabs -->
                            <ul class="nav nav-tabs tabs customtab">
                                
                                <li class="active tab">
                                    <a href="#profile" data-toggle="tab"> <span class="visible-xs"><i class="fa fa-user"></i></span> <span class="hidden-xs">Profile</span> </a>
                                </li>
                                <li class="tab">
                                    <a href="#settings" data-toggle="tab" aria-expanded="false"> <span class="visible-xs"><i class="fa fa-cog"></i></span> <span class="hidden-xs">Edit Profile</span> </a>
                                </li>
                            </ul>
                            <!-- /.tabs -->
                            <div class="tab-content">
                               
                                <!-- .tabs2 -->
                                <div class="tab-pane active" id="profile">
                                    
                                    <h6 class="m-t-30">Profile Information</h6>
                                   <hr>
                                 
                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Phone Number</div>
                                    <div class="col-md-7 col-xs-12">'.$row['phone'].'</div>
                                    </div>
                                    <hr>
                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Gender</div>
                                    <div class="col-md-7 col-xs-12">'.$row['sex'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Birthday</div>
                                    <div class="col-md-7 col-xs-12">'.$row['dob'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Residential Address</div>
                                    <div class="col-md-7 col-xs-12">'.$row['address'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">City/State</div>
                                    <div class="col-md-7 col-xs-12">'.$row['city'].', '.$row['state'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Office Address</div>
                                    <div class="col-md-7 col-xs-12">'.$row['officeaddress'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-12 col-xs-12"><h6 class="m-t-30">Bank Account Details</h6></div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Bank Name</div>
                                    <div class="col-md-7 col-xs-12">'.$row['bank'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Account Nunmber</div>
                                    <div class="col-md-7 col-xs-12">'.$row['accountno'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Account Name</div>
                                    <div class="col-md-7 col-xs-12">'.$row['accname'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-12 col-xs-12"><h6 class="m-t-30">Referral Information</h6></div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Referral ID</div>
                                    <div class="col-md-7 col-xs-12">'.$row['user'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Referral Link</div>
                                    <div class="col-md-7 col-xs-12">https://smilewecarengo.com/signup.php?ref='.$row['user'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Share on WhatsApp<br><br></div>
                                    <div class="col-md-7 col-xs-12"><a href="whatsapp://send?text=It\'s all about financial empowerment. We can make you smile because we care. Join us now at @    
https://smilewecarengo.com/signup.php?ref='.$row['user'].'" data-action="share/whatsapp/share" class="btn btn-success">Share on WhatsApp</a></div>
                                    </div>
                                    <hr>

                                </div>
                                <!-- /.tabs2 -->
                                <!-- .tabs3 -->
                                <div class="tab-pane" id="settings">
                                 <form method="post" class="form-horizontal">
                                        <h5 class="m-t-30">Update Profile</h5>
                                    <hr>
                                       
                                        
                                        <div class="form-group">
                                            <label class="col-md-12">Phone Number</label>
                                            <div class="col-md-12">
                                                <input type="text" name="phone" class="form-control" value="'.$row['phone'].'"> </div>
                                        </div>
<div class="form-group">
                                            <label class="col-md-12">Residential Address</label>
                                            <div class="col-md-12">
                                                <input type="text" name="address" class="form-control" value="'.$row['address'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">State</label>
                                            <div class="col-md-12">
                                                <input type="text" name="state" class="form-control" value="'.$row['state'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">City</label>
                                            <div class="col-md-12">
                                                <input type="text" name="city" class="form-control" value="'.$row['city'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Bank</label>
                                            <div class="col-md-12">
                                                <input type="text" name="bank" class="form-control" value="'.$row['bank'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Account Number</label>
                                            <div class="col-md-12">
                                                <input type="text" name="accountno" class="form-control" value="'.$row['accountno'].'"> </div>
                                        </div>
                                      

                                         <div class="form-group">
                                            <div class="col-sm-12">
                                                <button type="submit" name="UpdateUser" class="btn btn-success">Save Update</button>
                                            </div>
                                        </div>

                                       
                                    </form>


                                    <form method="post" class="form-horizontal">
                                        <h5 class="m-t-30">Password Reset</h5>
                                    <hr>
                                        <div class="form-group">
                                            <label class="col-md-12">Old Password</label>
                                            <div class="col-md-12">
                                                <input type="password" placeholder="" name="currentpass" class="form-control"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="example-email" class="col-md-12">New Password</label>
                                            <div class="col-md-12">
                                                <input type="password" placeholder="" class="form-control" name="newpass" id="example-email"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Confirm Password</label>
                                            <div class="col-md-12">
                                                <input type="password" name="newpass2" class="form-control"> </div>
                                        </div>
                                         <div class="form-group">
                                            <div class="col-sm-12">
                                                <button type="submit" name="changePassword" class="btn btn-success">Reset Password</button>
                                            </div>
                                        </div>

                                       
                                    </form>

                                     <h5 class="m-t-30">Update Profile Passport Photograph</h5>
                                    <hr>
                                    <form method="post"  enctype="multipart/form-data">
                                    <div class="row">
                    <div class="col-sm-6 ol-md-6 col-xs-12">
                      
                          
                            <label for="input-file-max-fs">Maximum Size is 200kb</label>
                            <input type="file" name="image" id="input-file-max-fs" class="dropify" data-max-file-size="200K" required /> </div>
                    </div>
                
                 <div class="form-group">
                                            <div class="col-sm-12">
                                                <button class="btn btn-success" name="updatePhoto">Update Photograph</button>
                                            </div>
                                        </div>


                                </div>
                                </form>
                                <!-- /.tabs3 -->
                            </div>
                        </div>
                    </div>';
	return $$a;
}



function userProfileDataSearch($keys,$a){
	global $db;

	$sql=$db->query("SELECT * FROM user WHERE sn = '$keys' " )or die(mysqli_error()); 
$row=mysqli_fetch_assoc($sql);

$activate = ($row['status']==1)?'<button class="btn btn-danger" name="DeactivateUser" value="'.$row['id'].'">Deactivate '.ucwords($row['firstname'].' '.$row['lastname']).'</button>':'<button class="btn btn-success" name="DeactivateUser" value="'.$row['id'].'">Activate '.ucwords($row['firstname'].' '.$row['lastname']).'</button>';

$updatepin = ($this->pinMultiple($row['user'])>1)?'<br><br><br><br>
                       <p>UPDATE USER PIN</p><hr class="p-0">
                        <p>PIN <input type="text" name="pin" class="form-control" value="'.$row['pin'].'"></p><p><br><button class="btn btn-primary" name="UpdatePin" value="'.$row['id'].'">Update PIN for '.ucwords($row['firstname'].' '.$row['lastname']).'</button></p><p><br></p>'.$this->pinMultiple2($row['user']):'';

$data = '                        <div class="col-md-4 col-xs-12">
                        <div class="white-box">
                            <div class="user-bg"> <img width="100%" alt="user" src="photo/'.$row['photo'].'">
                               
                                    <div class="user-content text-center">
                                        
                                        <b><br>'.ucwords($row['firstname'].' '.$row['lastname']).'</b>
                                        <h5 class="">'.$row['email'].'</h5> </div>
                               
                            </div>

                             <hr>
                               
                                <!-- .row -->
                                <div class="row text-center m-t-10">
                                    <div class="col-md-6 col-xs-6 b-r"><strong>Sponsor</strong>
                                        <p>'.$this->wildUserName($row['sponsor']).'</p>
                                    </div>
                                    <div class="col-md-6 col-xs-6"><strong>Upline</strong>
                                        <p>'.$this->wildUserName($row['a1']).'</p>
                                    </div>
                                </div>
                                <!-- /.row -->

                      

                            
                        </div>  
                        <b>SEND MESSAGE TO USER<br></b>
                        <form method="post">
                        <p><br>Message Title: <input class="form-control"  name="subject"></p>
                        <p><br>Message: <textarea class="form-control" rows="10" name="msg"></textarea></p>
                        <p><br><button class="btn btn-primary pull-right" name="SendUserMessage" value="'.$row['id'].'">Send Message to '.ucwords($row['firstname'].' '.$row['lastname']).'</button></p></form>


                        <form method="post">
                       <br><br><br><br><br>
                       <p>DEACTIVATE/ACTIVATE USER</p><hr class="p-0">
                        <p><br>'.$activate.'</p></form>

                        <form method="post">
                       '.$updatepin.'</form>

                    </div>';



               



                    $data2 = '<div class="col-md-8 col-xs-12">
                        <div class="white-box">
                            <!-- .tabs -->
                            <ul class="nav nav-tabs tabs customtab">
                                
                                <li class="active tab">
                                    <a href="#profile" data-toggle="tab"> <span class="visible-xs"><i class="fa fa-user"></i></span> <span class="hidden-xs">Profile</span> </a>
                                </li>
                                <li class="tab">
                                    <a href="#settings" data-toggle="tab" aria-expanded="false"> <span class="visible-xs"><i class="fa fa-cog"></i></span> <span class="hidden-xs">Edit Profile</span> </a>
                                </li>
                            </ul>
                            <!-- /.tabs -->
                            <div class="tab-content">
                               
                                <!-- .tabs2 -->
                                <div class="tab-pane active" id="profile">
                                    
                                    <h6 class="m-t-30">Profile Information</h6>
                                   <hr>
                                 
                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Phone Number</div>
                                    <div class="col-md-7 col-xs-12">'.$row['phone'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Gender</div>
                                    <div class="col-md-7 col-xs-12">'.$row['sex'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Birthday</div>
                                    <div class="col-md-7 col-xs-12">'.$row['dob'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Residential Address</div>
                                    <div class="col-md-7 col-xs-12">'.$row['address'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">City/State</div>
                                    <div class="col-md-7 col-xs-12">'.$row['city'].', '.$row['state'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Office Address</div>
                                    <div class="col-md-7 col-xs-12">'.$row['officeaddress'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-12 col-xs-12"><h6 class="m-t-30">Bank Account Details</h6></div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Bank Name</div>
                                    <div class="col-md-7 col-xs-12">'.$row['bank'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Account Nunmber</div>
                                    <div class="col-md-7 col-xs-12">'.$row['accountno'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Account Name</div>
                                    <div class="col-md-7 col-xs-12">'.$row['accname'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-12 col-xs-12"><h6 class="m-t-30">Referral Information</h6></div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Referral ID</div>
                                    <div class="col-md-7 col-xs-12">'.$row['user'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Referral Link</div>
                                    <div class="col-md-7 col-xs-12">https://smilewecarengo.com/signup.php?ref='.$row['user'].'</div>
                                    </div>
                                    <hr>

                                    <div class="row">
                                    <div class="col-md-5 col-xs-12 font-12">Share on WhatsApp<br><br></div>
                                    <div class="col-md-7 col-xs-12"><a href="whatsapp://send?text=It\'s all about financial empowerment. We can make you smile because we care. Join us now at @    
https://smilewecarengo.com/signup.php?ref='.$row['user'].'" data-action="share/whatsapp/share" class="btn btn-success">Share on WhatsApp</a></div>
                                    </div>
                                    <hr>

                                </div>
                                <!-- /.tabs2 -->
                                <!-- .tabs3 -->
                                <div class="tab-pane" id="settings">

                                    <form method="post" class="form-horizontal">
                                        <h5 class="m-t-30">Update Profile</h5>
                                    <hr>
                                        <div class="form-group">
                                            <label class="col-md-12">Other Names</label>
                                            <div class="col-md-12">
                                                <input type="text" placeholder="" name="lastname" class="form-control" value="'.$row['lastname'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="example-email" class="col-md-12">Email</label>
                                            <div class="col-md-12">
                                                <input type="text" placeholder="" class="form-control" name="email" value="'.$row['email'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Phone Number</label>
                                            <div class="col-md-12">
                                                <input type="text" name="phone" class="form-control" value="'.$row['phone'].'"> </div>
                                        </div>
<div class="form-group">
                                            <label class="col-md-12">Residential Address</label>
                                            <div class="col-md-12">
                                                <input type="text" name="address" class="form-control" value="'.$row['address'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">State</label>
                                            <div class="col-md-12">
                                                <input type="text" name="state" class="form-control" value="'.$row['state'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">City</label>
                                            <div class="col-md-12">
                                                <input type="text" name="city" class="form-control" value="'.$row['city'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Bank</label>
                                            <div class="col-md-12">
                                                <input type="text" name="bank" class="form-control" value="'.$row['bank'].'"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Account Number</label>
                                            <div class="col-md-12">
                                                <input type="text" name="accountno" class="form-control" value="'.$row['accountno'].'"> </div>
                                        </div>
                                      

                                         <div class="form-group">
                                            <div class="col-sm-12">
                                                <button type="submit" name="UpdateUser2" class="btn btn-success">Save Update</button>
                                            </div>
                                        </div>

                                       
                                    </form>


                                    <form method="post" class="form-horizontal">
                                        <h5 class="m-t-30">Password Reset</h5>
                                    <hr>
                                        <div class="form-group">
                                            <label class="col-md-12">Admin Password</label>
                                            <div class="col-md-12">
                                                <input type="password" placeholder="" name="currentpass" class="form-control"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label for="example-email" class="col-md-12">New Password</label>
                                            <div class="col-md-12">
                                                <input type="password" placeholder="" class="form-control" name="newpass" id="example-email"> </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-md-12">Confirm Password</label>
                                            <div class="col-md-12">
                                                <input type="password" name="newpass2" class="form-control"> </div>
                                        </div>
                                         <div class="form-group">
                                            <div class="col-sm-12">
                                                <button type="submit" name="changePassword2" class="btn btn-success">Reset Password</button>
                                            </div>
                                        </div>

                                       
                                    </form>



                                     <h5 class="m-t-30">Update Profile Passport Photograph</h5>
                                    <hr>
                                    <form method="post"  enctype="multipart/form-data">
                                    <div class="row">
                    <div class="col-sm-6 ol-md-6 col-xs-12">
                      
                          
                            <label for="input-file-max-fs">Maximum Size is 200kb</label>
                            <input type="file" name="image" id="input-file-max-fs" class="dropify" data-max-file-size="200K" required /> </div>
                    </div>
                
                 <div class="form-group">
                                            <div class="col-sm-12">
                                                <button class="btn btn-success" name="updatePhoto2">Update Photograph</button>
                                            </div>
                                        </div>


                                </div>
                                </form>
                                <!-- /.tabs3 -->
                            </div>
                        </div>
                    </div>';
	return $$a;
}














function  createPin(){
	global $report,$db,$signup,$userKey;

$num=sanitize($_POST['no-of-pin']);
for ($a = 1; $a<=$num; $a++){ 
$pin = strtoupper($signup->win_hash(10));
	$sql = $db->query("INSERT INTO pin(pin,rep,tm) VALUES('$pin','$userKey','1') ");
}
$report = $num.' PINs successfully generated';
return;
}

	
}

$profile = new Profile; 

//end of Bonus Class



?>

?>