<?php

	include('../config.php');
	session_start();

	$userid = intval($_SESSION['user_login']);
	
	
		//Admin info
		$stmt=$pdo->prepare("SELECT * FROM users WHERE userid = :userid");
		$stmt->bindParam("userid", $userid, PDO::PARAM_STR);
		$stmt->execute();
		$userVal=$stmt->fetch();
		
		
		
		
		
	

	

//UPDATE PROFILE IMAGE - for admin

if(isset($_FILES["profilepix"]["name"])){


//Check and remove previous image on folder
 $query=$pdo->prepare("SELECT profilepix FROM users WHERE userid=:userid");
 $query->bindParam(":userid", $userid, PDO::PARAM_STR);
 $query->execute();
 $prev = $query->fetch();
 if(!empty($prev["profilepix"]))
 {
	@unlink('../img/users/'.$prev["profilepix"]);
 }
 
	
 //$output = '';
 sleep(1);
 for($count=0; $count<count($_FILES["profilepix"]["name"]); $count++)
 {
  $profilepix = $_FILES["profilepix"]["name"][$count];
  $tmp_name = $_FILES["profilepix"]['tmp_name'][$count];
  $file_array = explode(".", $profilepix);
  $file_extension = end($file_array);
  if(file_already_uploaded($profilepix, $pdo))
  {
   $profilepix = $file_array[0] . '-'. rand() . '.' . $file_extension;
  }
  $location = '../img/users/' . $profilepix;
  if(move_uploaded_file($tmp_name, $location))
  {
   
   $stmt=$pdo->prepare("UPDATE users SET profilepix=(:profilepix) WHERE userid=:userid");
   $stmt->bindParam(":profilepix", $profilepix, PDO::PARAM_STR);
   $stmt->bindParam(":userid", $userid, PDO::PARAM_STR);
   $stmt->execute();
   if($stmt){
	   
		//Load Image
		$sql=$pdo->prepare("SELECT profilepix FROM users WHERE userid=:userid");
		$sql-> bindParam(':userid', $userid, PDO::PARAM_STR);
		$sql->execute();
		$row=$sql->fetch();
		$profilepix = (!empty($row["profilepix"]) ? "../img/users/".$row["profilepix"]: "../img/avatar.png");
	
		echo 
		'<img src="'.$profilepix.'" alt="User Avatar" class="img-size-50 mr-3 img-circle" style="height:120px;width:120px; border-radius:50%;border:2px solid #d3d6d7">';
	
  }
   
  }
 }
}


function file_already_uploaded($profilepix, $pdo)
{
 $userid = $_SESSION["user_login"];
 
 $statement = $pdo->prepare("SELECT profilepix FROM users WHERE userid=:userid");
 $statement->bindParam(":userid", $userid, PDO::PARAM_STR);
 $statement->execute();
 $getStmt = $statement->fetch();
 if(!empty($getStmt["profilepix"]))
 {
  return true;
 }
 else
 {
  return false;
 }
}










	//UPDATE ADMIN PROFILE

	
	if(isset($_POST["update"])){
			
	$fullName = htmlspecialchars(str_ireplace('  ','',$_POST["fullName"]));
	$username = htmlspecialchars(str_ireplace('  ','',$_POST["username"]));
	$email = htmlspecialchars($_POST["email"]);
	$address = htmlspecialchars(trim($_POST["address"]));
	$phone = htmlspecialchars(trim($_POST["phone"]));
	$country = htmlspecialchars(trim($_POST["country"]));
	$btc = htmlspecialchars(trim($_POST["btc"]));
	$ethereum = htmlspecialchars(trim($_POST["ethereum"]));
	$usdt = htmlspecialchars(trim($_POST["usdt"]));
	$usdc = htmlspecialchars(trim($_POST["usdc"]));
	
	
	if($fullName =="" || $fullName ==" " || $fullName =="   " || empty($fullName)){
		$error[] = "<br>Please enter your full name.<br><script>$('#fullName').focus()</script>";
	}
	elseif(!preg_match('/^[a-zA-Z-_.\s\']+$/',$fullName)){
		 $error[] = "<br>Name must not contain special characters.<br><script>$('#fullName').focus()</script>";
	  }
	if($username =="" || $username ==" " || $username =="   " || empty($username)){
		$error[] = "<br>Username is required<br><script>$('#username').focus()</script>";
	}
	elseif(!preg_match('/^[a-zA-Z-0-9_.\s\']+$/',$username)){
		  $error[] = "<br> Username must not contain special characters.<br><script>$('#username').focus()</script>";
	  }
	  
	 	
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{
		$stmt = $pdo->prepare("
		UPDATE users SET fullName=:fullName,email=:email,address=:address,username=:username,phone=:phone,
		country=:country,btc=:btc,ethereum=:ethereum,usdt=:usdt,usdc=:usdc WHERE userid=:userid");
		
		$stmt->bindParam(":fullName",$fullName,PDO::PARAM_STR);
		$stmt->bindParam(":email",$email,PDO::PARAM_STR);
		$stmt->bindParam(":address",$address,PDO::PARAM_STR);
		$stmt->bindParam(":username",$username,PDO::PARAM_STR);
		$stmt->bindParam(":phone",$phone,PDO::PARAM_STR);
		$stmt->bindParam(":country",$country,PDO::PARAM_STR);
		$stmt->bindParam(":btc",$btc,PDO::PARAM_STR);
		$stmt->bindParam(":ethereum",$ethereum,PDO::PARAM_STR);
		$stmt->bindParam(":usdt",$usdt,PDO::PARAM_STR);
		$stmt->bindParam(":usdc",$usdc,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//Fade Out Form and Show
			
				$("#select-btn").fadeOut();
				$("#updateForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Profile Updated");
					
				});	
			</script>
			
			
			';
		}
		}
		
		}
		
		





	
	
	///UPDATE PASSWORD - For Admin
		
	if(isset($_POST["updatePass"])){	
		
	$oldPassword = htmlspecialchars($_POST["oldPassword"]);
	$password = htmlspecialchars($_POST["password"]);
	$ConfirmPassword = htmlspecialchars($_POST["ConfirmPassword"]);
		
	$checkPassword = password_verify($oldPassword, $userVal["password"]);
		
	if(empty($oldPassword)){
		$error[] = "<br>Enter your current password<br><script>$('#oldPassword').focus()</script>";
	}
	elseif(empty($password)){
		$error[] = "<br>Enter your new password<br><script>$('#password').focus()</script>";
	}
	elseif(empty($ConfirmPassword)){
		$error[] = "<br>Confirm password<br><script>$('#ConfirmPassword').focus()</script>";
	}
	
	elseif(strlen($password)<6){
			$error[] = "<br>Password must be upto 6 characters<br><script>$('#password').focus()</script>";
		}
		
	elseif($ConfirmPassword != $password){
			$error[] = "<br>New passwords did match<br><script>$('#ConfirmPassword').focus()</script>";
		}
			
	elseif($checkPassword != $oldPassword){
			$error[] = "<br>Incorrect password supplied<br><script>$('#oldPassword').focus()</script>";
		}
	
		
		
		
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{

			try{
			
				$newPassword = password_hash($password, PASSWORD_DEFAULT);
				
				$stmt=$pdo->prepare("UPDATE users SET password=(:password) WHERE userid=:userid");
				
				$stmt->bindParam(":password",$newPassword,PDO::PARAM_STR);
				$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
				$stmt->execute();
				
				if($stmt){
			
			echo '
			<script>
			//Fade Out Form
			
				$("#passwordForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Successful!");
				});	
			</script>
			
			
			';
		}
			
			}catch(PDOException $e){
				echo "Error occured " . $e->getMessage();
			}
				
			}
		
		
		}
		
		
		


















//======================================================================
//ADMIN CONTROLS













	//SUSPEND USER ACCOUNT

	if(isset($_POST["disableStatus"])){
			
	
	if($_POST["disableStatus"] == "enable"){
		$disable = "";
	}else{
		$disable = htmlspecialchars($_POST["disableStatus"]);
	}
		
	
	$userid = intval($_POST["userid"]);
	
		
		
		$stmt = $pdo->prepare("UPDATE users SET disable=:disable WHERE userid=:userid");
		$stmt->bindParam(":disable",$disable,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){
			
		if($disable =="disabled"){
			
			echo "disabled";
		
		}else{
			
			echo 'enabeled';
		}
		
		
		}
	}




		
		
		
	
	
	








	//SUSPEND USER FROM WITHRAWING

	if(isset($_POST["withdrawStatus"])){
			
	
	if($_POST["withdrawStatus"] == "enableWithdraw"){
		$suspendWithdrawal = "";
	}else{
		$suspendWithdrawal = htmlspecialchars($_POST["withdrawStatus"]);
	}
		
	
		$userid = intval($_POST["userid"]);
	
		
		
		$stmt = $pdo->prepare("UPDATE users SET suspendWithdrawal=:suspendWithdrawal WHERE userid=:userid");
		$stmt->bindParam(":suspendWithdrawal",$suspendWithdrawal,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){
			
		if($suspendWithdrawal =="suspended"){
			
			echo "suspended";
		
		}else{
			
			echo 'enabeled';
		}
		
		
		}
	}











	
		
		
		
	
	//APPROVE WITHRAWAL AND INVESTMENT REQUESTs, Update balance and calculate percentage for profit table

	if(isset($_POST["approved"])){
			
	$status = htmlspecialchars($_POST["approved"]);
	$transactID = intval($_POST["transactID"]);
	
		
		
		$stmt = $pdo->prepare("UPDATE transactions SET status=:status WHERE id=:id");
		$stmt->bindParam(":status",$status,PDO::PARAM_STR);
		$stmt->bindParam(":id",$transactID,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//swap Button
				
				//hide approve btn
				$("#approve_'.$transactID.'").addClass("display-none");
				
				//show Approved btn
				$("#approved_'.$transactID.'").removeClass("display-none");
					
					
				
				//Once Approved change the delicne btn to null
				$("#decline_'.$transactID.', #declined_'.$transactID.'").addClass("display-none");
				
				$("#cantD_'.$transactID.'").removeClass("display-none");
					
			</script>';
		
		
		
		
		
		//Now if transaction is approved (either of investment or withdrawal) update the user account deposit or withdrawals columns respectively
		//*Note $transactID = is the ID for the curently approved transaction in the users "transaction" table
		
		//get the transaction type, amount and the user 
		$stmt=$pdo->prepare("SELECT * FROM transactions WHERE id = :id");
		$stmt->bindParam(":id",$transactID, PDO::PARAM_STR);
		$stmt->execute();
		$trans=$stmt->fetch();
		
		//transaction Values
		$type = $trans["type"];
		$dateTime = $trans["dateTime"];
		$amount = intval($trans["amount"]);
		$plan = $trans["plan"];
		$TheUser = intval($trans["userid"]);
		
		
		
		//Get the current balances in the user 'Account' table
		$stmt=$pdo->prepare("SELECT * FROM account WHERE userid=:userid");
		$stmt->bindParam(":userid",$TheUser, PDO::PARAM_STR);
		$stmt->execute();
		$userBal=$stmt->fetch();
		
		$accountBal = intval($userBal["balance"]);		//current account Balance
		$depositBal = intval($userBal["deposit"]);		//current deposit balance
		
		
		
		
		
		//if the transaction type is withdrawal, substract the withdrawal amount from the current balance and update the balance column
		if($type == "withdrawal"){
		//substract withdrawal amount from user bal
		$newBal = $accountBal - $amount;
			
		$stmt = $pdo->prepare("UPDATE account SET balance=:newBal, dateTime=:dateTime WHERE userid=:userid");
		$stmt->bindParam(":newBal",$newBal,PDO::PARAM_STR);
		$stmt->bindParam(":dateTime",$dateTime,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$TheUser,PDO::PARAM_STR);
		$stmt->execute();	
		
		
		//============================
		//Send a WITHRAWAL mail
		require_once("../mails/admin_approve_Invetment_withdrawal.php");
		
		
		}
		
		
		//if the transaction type is investment, add the investment amount to the current deposit balance 
		//Also increase the user "account Balance"
		elseif($type == "investment"){
		
		//Add the current active deposit balance in the "account" table to the investment amount from user 
		$newDepositBal =  $depositBal + $amount;
		
		//Add the investment amount to the previous balance
		$newBal = $accountBal + $amount;
		
		$stmt = $pdo->prepare("UPDATE account SET deposit=:newDepositBal, balance=:newBal, dateTime=:dateTime WHERE userid=:userid");
		$stmt->bindParam(":newDepositBal",$newDepositBal,PDO::PARAM_STR);
		$stmt->bindParam(":newBal",$newBal,PDO::PARAM_STR);
		$stmt->bindParam(":dateTime",$dateTime,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$TheUser,PDO::PARAM_STR);
		$stmt->execute();
		
		
		
		//============================
		//Send an INVESTMENT mail
		require_once("../mails/admin_approve_Invetment_withdrawal.php");
		
		
		
		
		
		//CALCULATE and insert THE Percentage value of user deposit to "duedate" table
		

		//check first if there's a previous deposit on "duedate" Table by user as user is allowed to deposit only 5times at max per day
		$stmt=$pdo->prepare("SELECT * FROM duedate WHERE userid=:userid");
		$stmt->bindParam(":userid",$TheUser, PDO::PARAM_STR);
		$stmt->execute();
		$prevDue=$stmt->fetch();
		
		
			//if user has deposited b4 within same day Update column instead of insert
			if($stmt->rowCount() > 0){
			
			$oldDeposit = intval($prevDue["deposit"]);		//get previous deposit
			$newCount = intval($prevDue["count"] +1);		//get previous count - (i.e max number of deposit per day) and add 1 to increment
			$oldPlan = $prevDue["plan"];					//get old plan on DB
			
			
			//add the previous deposit to the current deposit by user and calculate the percentage
			$newAmount = $amount + $oldDeposit;
			
			
			
			//Get the percentage profit of the old and new deposits	- that's by default, depending on selected plan
			
			//FOR BRONZE
			if($oldPlan == "Bronze" AND $plan == "Bronze"){
				
			$ThePlan = 	"Bronze";											//Upgrade Plan if higher plan was invested
			
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(4, $newAmount);
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");							//Approved date - current date
			}
			
			
			
			//FOR SILVER
			elseif($oldPlan == "Silver" || $oldPlan == "Silver" AND $plan == "Bronze" || $plan == "Silver"){
				
				$ThePlan = 	"Silver";										//Upgrade Plan if higher plan was invested
				
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(6, $newAmount);
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			}
			
			
			
			//FOR GOLD
			elseif($oldPlan == "Gold" || $oldPlan == "Silver" || $oldPlan =="Bronze" AND 
					 $plan =="Bronze" || $plan == "Silver" || $plan == "Gold" ){
				
				$ThePlan = 	"Gold";									//Upgrade Plan if higher plan was invested
				
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(8, $newAmount);
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			}
			
			
			
			//FOR PLATINUM
			elseif($oldPlan =="Bronze" || $oldPlan == "Silver" || $oldPlan == "Gold" || $oldPlan == "Platinum" AND
					$plan =="Bronze" || $plan == "Silver" || $plan == "Gold" || $plan =="Platinum" ){
			
				$ThePlan = 	"Platinum";									//Upgraded Plan based on highest Bid
			
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(10, $newAmount);
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			}
			
			
		    
		    //FOR VIP
			elseif($oldPlan =="Bronze" || $oldPlan == "Silver" || $oldPlan == "Gold" || $oldPlan == "Platinum" || $oldPlan == "Vip" AND
					$plan =="Bronze" || $plan == "Silver" || $plan == "Gold" || $plan =="Platinum" || $plan =="Vip" ){
			
				$ThePlan = 	"Vip";									//Upgraded Plan based on highest Bid
			
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(10, $newAmount);
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			}
		
		
		
		
		
		
		//Update the "Duedate" table with the new values
		
		$stmt = $pdo->prepare("UPDATE duedate SET deposit=:deposit, percentage_profit=:percentage_profit, plan=:plan, 
								deposit_date=:deposit_date, timing=:timing, due_date=:due_date, count=:count WHERE userid=:userid");
		   
		$stmt->bindParam(":deposit",$newAmount,PDO::PARAM_STR);
		$stmt->bindParam(":percentage_profit",$percentProfit,PDO::PARAM_STR);
		$stmt->bindParam(":plan",$ThePlan,PDO::PARAM_STR);
		$stmt->bindParam(":deposit_date",$deposit_date,PDO::PARAM_STR);
		$stmt->bindParam(":timing",$deposit_date,PDO::PARAM_STR);
		$stmt->bindParam(":due_date",$due_date,PDO::PARAM_STR);
		$stmt->bindParam(":count",$newCount,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$TheUser,PDO::PARAM_STR);
		$stmt->execute();
		
		
		

		//if user has no previous deposit in "dudate" table INSERT instead
		}else{
			
		
		
		
			//Get the percentage profilt of the new deposits	- that's by default, depending on selected plan
			//% profilt - Note* $amount is the user current deposit we defined above
			
			//FOR BRONZE
			if($plan == "Bronze"){
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(4, $amount);
			
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");							//Approved date - current date
			$ThePlan = 	"Bronze";										//Selected Plan
			}
			
			//FOR SILVER
			elseif($plan == "Silver"){
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(6, $amount);
			
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			$ThePlan = 	"Silver";									//Selected Plan
			}
			
			//FOR GOLD
			elseif($plan == "Gold"){
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(8, $amount);
			
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			$ThePlan = 	"Gold";									//Selected Plan
			}
			
			//FOR PLATINUM
			elseif($plan == "Platinum"){
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(10, $amount);
			
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			$ThePlan = 	"Platinum";									//Selected Plan
			}
			
		    //FOR VIP
			elseif($plan == "Vip"){
			function percentageVal($percentage, $userDeposits){
			 return ($percentage * $userDeposits) / 100;
			}
			$percentProfit = percentageVal(15, $amount);
			
			$due_date = date("Y-m-d H:i:s", strtotime("+3 days"));		//to get the due date, add the plan period to the current date
			$deposit_date = date("Y-m-d H:i:s");						//Approved date - current date
			$ThePlan = 	"Vip";									//Selected Plan
			}
			
		
		
		
		
		$count = 1;							// The max deposit per day counter (max deposit is 5)
		
		$stmt=$pdo->prepare("INSERT INTO  duedate (count,deposit,percentage_profit,plan,deposit_date,timing,due_date,userid) 
							VALUES (:count,:deposit,:percentage_profit,:plan,:deposit_date,:timing, :due_date,:userid)");
		$stmt->bindParam(":count", $count, PDO::PARAM_STR);
		$stmt->bindParam(":deposit", $amount, PDO::PARAM_STR);
		$stmt->bindParam(":percentage_profit", $percentProfit, PDO::PARAM_STR);
		$stmt->bindParam(":plan", $ThePlan, PDO::PARAM_STR);
		$stmt->bindParam(":deposit_date", $deposit_date, PDO::PARAM_STR);
		$stmt->bindParam(":timing", $deposit_date, PDO::PARAM_STR);
		$stmt->bindParam(":due_date", $due_date, PDO::PARAM_STR);
		$stmt->bindParam(":userid", $TheUser, PDO::PARAM_STR);
		$stmt->execute();
		
		}
		
		
		
		
		
		
		
		
	
		}
		
		
		}
		}
				
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
	//DECLINE WITHRAWAL AND INVESTMENT REQUESTs

	if(isset($_POST["declined"])){
			
	$status = htmlspecialchars($_POST["declined"]);
	$transactID = intval($_POST["transactID"]);
	
		
		
		$stmt = $pdo->prepare("UPDATE transactions SET status=:status WHERE id=:id");
		$stmt->bindParam(":status",$status,PDO::PARAM_STR);
		$stmt->bindParam(":id",$transactID,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//swap Button
				
				//hide decline btn
				$("#decline_'.$transactID.'").addClass("display-none");
				
				//show declined btn
				$("#declined_'.$transactID.'").removeClass("display-none");
					
			</script>';
			
			
			//Send Email to user
			require_once("../mails/admin_decline_Invetment_withdrawal.php");
		
		
		}
	}
		
		
		
		
	
		
		
		
	










		//SITE LOCK
		
		if(isset($_POST["locked"])){
			
		$text = htmlspecialchars($_POST["text"]);
		$passCode = htmlspecialchars($_POST["passCode"]);
		$locked = htmlspecialchars($_POST["locked"]);
		
		
		$stmt=$pdo->prepare("SELECT * FROM maintenance WHERE locked ='locked' OR locked ='unlocked' ");
		$stmt->execute();
		$check=$stmt->rowCount();
		
		if($check >0){
			
		$stmt = $pdo->prepare("UPDATE maintenance SET text=:text, passCode=:passCode, locked=:locked");
		$stmt->bindParam(":text",$text,PDO::PARAM_STR);
		$stmt->bindParam(":passCode",$passCode,PDO::PARAM_STR);
		$stmt->bindParam(":locked",$locked,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){ 
		echo 1; 
		
			//Send Email to user
			require_once("../mails/admin_maintenance.php");
		}
		
		}else{
		
		$stmt = $pdo->prepare("INSERT INTO maintenance (text,passCode,locked)VALUES(:text,:passCode,:locked)");
		$stmt->bindParam(":text",$text,PDO::PARAM_STR);
		$stmt->bindParam(":passCode",$passCode,PDO::PARAM_STR);
		$stmt->bindParam(":locked",$locked,PDO::PARAM_STR);
		$stmt->execute();
		
		
		if($stmt){ 
		echo 1; 
		
			//Send Email to user
			require_once("../mails/admin_maintenance.php");
		}
		
		}
		
		}
		
		
		
		
		
		
		
		//UNLOCK SITE
		
		if(isset($_POST["unlocked"])){
			
		$stmt = $pdo->prepare("UPDATE maintenance SET locked='unlocked' WHERE locked ='locked' ");
		$stmt->execute();
		if($stmt){ echo 1; }
		}
		
		
		
		
		
		
		
		
		
		
		
		//Delete User
		
		if(isset($_POST["delid"])){
			
		$delid = $_POST["delid"];
			
		$stmt = $pdo->prepare("DELETE FROM users WHERE userid =:delid ");
		$stmt->bindParam(":delid",$delid,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){ echo 1; }
		
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//UPDATE USERS PROFILE

	
	if(isset($_POST["updateUser"])){
			
	$fullName = htmlspecialchars(str_ireplace('  ','',$_POST["fullName"]));
	$username = htmlspecialchars(str_ireplace('  ','',$_POST["username"]));
	$email = htmlspecialchars($_POST["email"]);
	$address = htmlspecialchars(trim($_POST["address"]));
	$phone = htmlspecialchars(trim($_POST["phone"]));
	$country = htmlspecialchars(trim($_POST["country"]));
	$btc = htmlspecialchars(trim($_POST["btc"]));
	$ethereum = htmlspecialchars(trim($_POST["ethereum"]));
	$usdt = htmlspecialchars(trim($_POST["usdt"]));
	$usdc = htmlspecialchars(trim($_POST["usdc"]));

	$theUser = intval($_POST["theUser"]);
	
	
	if($fullName =="" || $fullName ==" " || $fullName =="   " || empty($fullName)){
		$error[] = "<br>Please enter your full name.<br><script>$('#fullName').focus()</script>";
	}
	if (!preg_match('/^[a-zA-Z-_.\s\']+$/',$fullName)) {
    // Handle the case when the name contains special characters
} else {
    // Process the name when it's valid (including special characters)

	  }
	if($username =="" || $username ==" " || $username =="   " || empty($username)){
		$error[] = "<br>Username is required<br><script>$('#username').focus()</script>";
	}
	if (empty($username) || !preg_match('/^[a-zA-Z0-9-_.\s\']+$/',$username)) {
    // Handle the case when username is empty or contains special characters
} else {
    // Process the username when it's valid

	  }
	  
	 	
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{
		$stmt = $pdo->prepare("
		UPDATE users SET fullName=:fullName,email=:email,address=:address,username=:username,phone=:phone,
		country=:country,btc=:btc,ethereum=:ethereum,usdt=:usdt,usdc=:usdc WHERE userid=:userid");
		
		$stmt->bindParam(":fullName",$fullName,PDO::PARAM_STR);
		$stmt->bindParam(":email",$email,PDO::PARAM_STR);
		$stmt->bindParam(":address",$address,PDO::PARAM_STR);
		$stmt->bindParam(":username",$username,PDO::PARAM_STR);
		$stmt->bindParam(":phone",$phone,PDO::PARAM_STR);
		$stmt->bindParam(":country",$country,PDO::PARAM_STR);
		$stmt->bindParam(":btc",$btc,PDO::PARAM_STR);
		$stmt->bindParam(":ethereum",$ethereum,PDO::PARAM_STR);
		$stmt->bindParam(":usdt",$usdt,PDO::PARAM_STR);
		$stmt->bindParam(":usdc",$usdc,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$theUser,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//Fade Out Form and Show
			
				$("#select-btn").fadeOut();
				$("#updateForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("User Profile Updated");
					
				});	
			</script>
			
			
			';
		}
		}
		
		}
		
		


		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		// ================USER MANAGEMENT FUNDS ======================
		
		
		
		
		
		//Add Bonus
		
		if(isset($_POST["AddBonus"])){
		
		$amount = intval($_POST["amount"]);
		$user = intval($_POST["user"]);
	
		if(!preg_match('/^[0-9]+$/',$amount)){
		 $amount = 0;
		}
	
	
	
		//get user Balance//get users Acct Bal
		$stmt=$pdo->prepare("SELECT * FROM account WHERE userid = :userid");
		$stmt->bindParam(":userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$Act = $stmt->fetch();
		
		
		$newBalance = $amount + intval($Act["balance"]);
	
		$stmt = $pdo->prepare("UPDATE account SET balance=:balance WHERE userid=:userid");
		$stmt->bindParam(":balance",$newBalance,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			
			echo '
			<script>
			
				$(".Bbal").html('.$newBalance.');				//upate screen Balance
				$("#add").html("");								//remove the plus + sign
				
				$("#addBonus").slideUp(function(){
					$("#sucB").removeClass("display-none");
				});
			</script>';
			
		
		
		
		//Notify User if checkBox is Checked
		
		if(isset($_POST["notifyB"])){
		$message = htmlspecialchars($_POST["description"]);			//description as the message
		$serviceTitle = "Bonus Earnings";							//as the title
		$status = "unread";
		
		$query=$pdo->prepare("INSERT INTO contact (message, userid, receiver, status, serviceTitle, amount) 
								VALUES (:message, :userid, :receiver, :status, :serviceTitle, :amount)");
		$query->bindParam(":message", $message, PDO::PARAM_STR);
		$query->bindParam(":userid", $userid, PDO::PARAM_STR);
		$query->bindParam(":receiver", $user, PDO::PARAM_STR);
		$query->bindParam(":status", $status, PDO::PARAM_STR);
		$query->bindParam(":serviceTitle", $serviceTitle, PDO::PARAM_STR);
		$query->bindParam(":amount", $amount, PDO::PARAM_STR);
		$query->execute();
		}
		
		
		}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//Deduct Penalty
		
		if(isset($_POST["DeductPenal"])){
		
		$amount = intval($_POST["amount"]);
		$user = intval($_POST["user"]);
	
		if(!preg_match('/^[0-9]+$/',$amount)){
		 $amount = 0;
		}
	
	
	
		//get user Balance//get users Acct Bal
		$stmt=$pdo->prepare("SELECT * FROM account WHERE userid = :userid");
		$stmt->bindParam(":userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$Act = $stmt->fetch();
		
		
		$newBalance = intval($Act["balance"]) - $amount;
	
		$stmt = $pdo->prepare("UPDATE account SET balance=:balance WHERE userid=:userid");
		$stmt->bindParam(":balance",$newBalance,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			
			echo '
			<script>
			
				$(".Bbal").html('.$newBalance.');				//upate screen Balance
				$("#pen").html("");								//remove the plus + sign
				
				$("#addPenalty").slideUp(function(){
					$("#sucP").removeClass("display-none");
				});
			</script>';
			
			
			
			
		
		//Notify User if checkBox is Checked
		
		if(isset($_POST["notifyP"])){
		$message = htmlspecialchars($_POST["description"]);			//description as the message
		$serviceTitle = "Penalty";									//as the title
		$status = "unread";
		

		$query=$pdo->prepare("INSERT INTO contact (message, userid, receiver, status, serviceTitle, amount) 
								VALUES (:message, :userid, :receiver, :status, :serviceTitle, :amount)");
		$query->bindParam(":message", $message, PDO::PARAM_STR);
		$query->bindParam(":userid", $userid, PDO::PARAM_STR);
		$query->bindParam(":receiver", $user, PDO::PARAM_STR);
		$query->bindParam(":status", $status, PDO::PARAM_STR);
		$query->bindParam(":serviceTitle", $serviceTitle, PDO::PARAM_STR);
		$query->bindParam(":amount", $amount, PDO::PARAM_STR);
		$query->execute();
		}
		
			
		}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		//ADD Referral Commision
		
		if(isset($_POST["RefCommision"])){
		
		$amount = intval($_POST["amount"]);
		$user = intval($_POST["user"]);
	
		if(!preg_match('/^[0-9]+$/',$amount)){
		 $amount = 0;
		}
	
	
	
		//get user Balance
		$stmt=$pdo->prepare("SELECT * FROM account WHERE userid = :userid");
		$stmt->bindParam(":userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$Act = $stmt->fetch();
		
		
		$newBalance = intval($Act["balance"]) + $amount;
	
		$stmt = $pdo->prepare("UPDATE account SET balance=:balance WHERE userid=:userid");
		$stmt->bindParam(":balance",$newBalance,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			
			echo '
			<script>
			
				$(".Bbal").html('.$newBalance.');				//upate screen Balance
				$("#reff").html("");								//remove the plus + sign
				
				$("#addRef").slideUp(function(){
					$("#sucR").removeClass("display-none");
				});
			</script>';
			
			
		
		
		
		//Notify User if checkBox is Checked
		
		if(isset($_POST["notifyR"])){
		$message = htmlspecialchars($_POST["description"]);			//description as the message
		$serviceTitle = "Referral Commision";						//as the title
		$status = "unread";
		

		$query=$pdo->prepare("INSERT INTO contact (message, userid, receiver, status, serviceTitle, amount) 
								VALUES (:message, :userid, :receiver, :status, :serviceTitle, :amount)");
		$query->bindParam(":message", $message, PDO::PARAM_STR);
		$query->bindParam(":userid", $userid, PDO::PARAM_STR);
		$query->bindParam(":receiver", $user, PDO::PARAM_STR);
		$query->bindParam(":status", $status, PDO::PARAM_STR);
		$query->bindParam(":serviceTitle", $serviceTitle, PDO::PARAM_STR);
		$query->bindParam(":amount", $amount, PDO::PARAM_STR);
		$query->execute();
		}

		
		}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//INVEST FOR USER
	
	

	if(isset($_POST["customAmount"])){
		
	$ref = htmlspecialchars($_POST["ref"]);
	$user = intval($_POST["user"]);
	
	
	if(empty($_POST["amount"])){
		$amount = htmlspecialchars($_POST["customAmount"]);
	}else{
		$amount = htmlspecialchars($_POST["amount"]);
	}
	
	
	
	
	
	 //$100 - $999	-			Bronze
	 //$1,000 - $4,999	-		Silver
	 //$5,000 - $49,999	-	    Gold
	 //$50,000 - $149,999	-	Platinum
	 //$150,000 - Unlimited	-	Vip
	  
	  //determine the plan user selected
	  switch(true){
		  
		  //Bronze
		  CASE $amount <= 999:
		  $plan = "Bronze";
		  break;
		  
		  //Silver
		  CASE ($amount > 999 && $amount <= 4999):
		  $plan = "Silver";
		  break;
		  
		  //Gold
		  CASE ($amount > 4999 && $amount <= 49999):
		  $plan = "Gold";
		  break;
		  
		  //Platinum
		  CASE ($amount > 49999 && $amount <= 149999):
		  $plan = "Platinum";
		  break;
		  
		  //Vip
		  CASE $amount > 149999:
		  $plan = "Vip";
		  break;
	  }
	  
	  
	  
	  
		$type = "investment";
		$status = "pending";
		$stmt = $pdo->prepare("INSERT INTO transactions (userid, ref, amount, type, plan, status) VALUES (:userid,:ref,:amount,:type,:plan,:status)");
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->bindParam(":ref",$ref,PDO::PARAM_STR);
		$stmt->bindParam(":amount",$amount,PDO::PARAM_STR);
		$stmt->bindParam(":type",$type,PDO::PARAM_STR);
		$stmt->bindParam(":plan",$plan,PDO::PARAM_STR);
		$stmt->bindParam(":status",$status,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){
			
			echo '
			<script>
			
				$("#addInvest").slideUp(function(){
					$("#sucI").removeClass("display-none");
					
				
				$("#plann").html("");								//remove the plus + sign
				$("#plans").html("<h4 style=color:#fff;>'.$plan. ' <i class=fas fa-bolt></i></h4>");							//Plan
				
					
				});
				
				
				
				
			</script>';
			
			
			
			
			
		//Notify User
		
		$message = htmlspecialchars($_POST["description"]);			//description as the message
		
		//Custome msg if it's empty
		if(empty($message)){
			$message = "Funded";
		}
		
		$serviceTitle = $plan." Investment Plan";					//as the title
		$status = "unread";
		$received = date("Y-m-d H:i:s");
		

		$query=$pdo->prepare("INSERT INTO contact (message, userid, receiver, status, serviceTitle, amount, received) 
								VALUES (:message, :userid, :receiver, :status, :serviceTitle, :amount, :received)");
		$query->bindParam(":message", $message, PDO::PARAM_STR);
		$query->bindParam(":userid", $userid, PDO::PARAM_STR);
		$query->bindParam(":receiver", $user, PDO::PARAM_STR);
		$query->bindParam(":status", $status, PDO::PARAM_STR);
		$query->bindParam(":serviceTitle", $serviceTitle, PDO::PARAM_STR);
		$query->bindParam(":amount", $amount, PDO::PARAM_STR);
		$query->bindParam(":received", $received, PDO::PARAM_STR);
		$query->execute();
			
		}
		
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
			
		
	
	///UPDATE PASSWORD FOR USER
		
	if(isset($_POST["updateUserPass"])){	
		
	$user = intval($_POST["user"]);
	$password = htmlspecialchars($_POST["password"]);
	$ConfirmPassword = htmlspecialchars($_POST["ConfirmPassword"]);
		

	if(empty($password)){
		$error[] = "<br>Enter your new password<br><script>$('#password').focus()</script>";
	}
	elseif(empty($ConfirmPassword)){
		$error[] = "<br>Confirm password<br><script>$('#ConfirmPassword').focus()</script>";
	}
	
	elseif(strlen($password)<6){
			$error[] = "<br>Password must be upto 6 characters<br><script>$('#password').focus()</script>";
		}
		
	elseif($ConfirmPassword != $password){
			$error[] = "<br>New passwords did match<br><script>$('#ConfirmPassword').focus()</script>";
		}
		
	
		
		
		
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{

			try{
			
				$newPassword = password_hash($password, PASSWORD_DEFAULT);
				
				$stmt=$pdo->prepare("UPDATE users SET password=(:password) WHERE userid=:userid");
				
				$stmt->bindParam(":password",$newPassword,PDO::PARAM_STR);
				$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
				$stmt->execute();
				
				if($stmt){
			
			echo '
			<script>
			//Fade Out Form
			
				$("#passwordForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Successful!");
				});	
			</script>';
			
			
			
		//get user details
		$stmt=$pdo->prepare("SELECT * FROM users WHERE userid = :userid");
		$stmt->bindParam("userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$userVal=$stmt->fetch();
		
	
	
			//Send Confirmation Email to user
			require_once("../mails/change_password.php");
			
			
		}
			
			}catch(PDOException $e){
				echo "Error occured " . $e->getMessage();
			}
				
			}
		
		
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//Cancel User Active Reading Deposit and Credit him
		
		if(isset($_POST["cancelDeposit"])){
			
			//cutome amount to credit user
			$earning = $_POST["earning"];
			$user = intval($_POST["user"]);
			
		
		//Get the percentage profit of user
		$stmt=$pdo->prepare("SELECT * FROM duedate WHERE userid = :userid");
		$stmt->bindParam("userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$dueDate=$stmt->fetch();
		if($stmt->rowCount()>0){
			
			
			
		//Get user current balance
		$stmt=$pdo->prepare("SELECT * FROM account WHERE userid=:userid");
		$stmt->bindParam(":userid",$user, PDO::PARAM_STR);
		$stmt->execute();
		$userBal=$stmt->fetch();
			
		
			
		$prevPercentage = $userBal["profits"];										//previous profit 
		$deposit = 0;																//Reset the active deposit to "0" for new deposit
		
		
		//get the previous user Profit and add it to the custome amount if isset or user default percentage if custom amount !isset
		if(empty($earning)){
		$percentProfit = $dueDate["percentage_profit"] + $prevPercentage;			
		}else{
			$percentProfit = $earning + $prevPercentage;
		}
		
		
		$stmt = $pdo->prepare("UPDATE account SET profits=:profits, deposit=:deposit WHERE userid=:userid");
		$stmt->bindParam(":profits",$percentProfit,PDO::PARAM_STR);
		$stmt->bindParam(":deposit",$deposit,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		
		//if successfully updated clear duedate table
		if($stmt){
		$stmt = $pdo->prepare("DELETE FROM duedate WHERE userid=:userid");
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		
		echo 1;
		}

		
		}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//Alter Percentage Readings
		
		if(isset($_POST["timing"])){
		
			$formatting = $_POST["formatting"];
			$timing = $_POST["timing"];
			$action = $_POST["action"];
			$earning = $_POST["earning"];
			$user = intval($_POST["user"]);
			
		
		//Get the percentage profit of user
		$stmt=$pdo->prepare("SELECT * FROM duedate WHERE userid = :userid");
		$stmt->bindParam("userid", $user, PDO::PARAM_STR);
		$stmt->execute();
		$dueDate=$stmt->fetch();
		if($stmt->rowCount()>0){
		
		
		//current deposit date
		$depositDate = $dueDate["timing"];
		
		
		//Add to current deposit dateTime if speedup was selected 
		if($action == "speed"){
			
			if($formatting == "day"){ 
				$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) + 60*60*24*$timing); 	//speed up in days
				$alterTime = "+ ".$timing. " days";
			}		
			
			elseif($formatting == "hour"){ 
					$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) + 60*60*$timing); 	//speed up in hours
					$alterTime = "+ ".$timing. " hours";
			}	
			
			elseif($formatting == "minute"){ 
					$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) + 60*$timing); 	//speed up in minutes
					$alterTime = "+ ".$timing. " minutes";
			}	
		}
			
			
			
		//Deduct from current deposit dateTime if delay was selected 
		if($action == "delay"){
			
			if($formatting == "day"){ 
				$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) - 60*60*24*$timing); 	//speed up in days
				$alterTime = "- ".$timing. " days";
			}		
			
			elseif($formatting == "hour"){ 
					$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) - 60*60*$timing); 	//speed up in hours
					$alterTime = "- ".$timing. " hours";
			}	
			
			elseif($formatting == "minute"){ 
					$newTiming = date("Y-m-d H:i:s", strtotime($depositDate) - 60*$timing); 		//speed up in minutes
					$alterTime = "- ".$timing. " minutes";
			}
		}
		
		
		
				//If "alterTime" column !empty
				
				if(!empty($dueDate["alterTime"])){
						$alterTime = $dueDate["alterTime"]. " ".$alterTime;
					}
			
			
			
		//if Percentage Profit(earning) empty - reset to current percent Profit
		if(empty($earning)){
			$earning = $dueDate["percentage_profit"];
		}
		
		$stmt = $pdo->prepare("UPDATE duedate SET percentage_profit=:percentage_profit, timing=:timing, alterTime=:alterTime 
								WHERE userid=:userid");
		$stmt->bindParam(":percentage_profit",$earning,PDO::PARAM_STR);
		$stmt->bindParam(":timing",$newTiming,PDO::PARAM_STR);
		$stmt->bindParam(":alterTime",$alterTime,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		
		//if successfully updated
		if($stmt){
		echo 1;
		}

		
		}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//Enable e-code withdrawal
		
		if(isset($_POST["eLocked"])){
			
		$passCode = intval($_POST["passCode"]);
		$user = intval($_POST["user"]);
			
		$stmt = $pdo->prepare("UPDATE users SET withdrawalPassCode=:withdrawalPassCode WHERE userid=:userid");
		$stmt->bindParam(":withdrawalPassCode",$passCode,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){ echo 1; }
		
		}
		
		
		
		
		
		
		
		//Disable e-code withdrawal
		
		if(isset($_POST["eUnlocked"])){
		
		$passCode = "";
		$user = intval($_POST["user"]);
		
		$stmt = $pdo->prepare("UPDATE users SET withdrawalPassCode=:withdrawalPassCode WHERE userid=:userid");
		$stmt->bindParam(":withdrawalPassCode",$passCode,PDO::PARAM_STR);
		$stmt->bindParam(":userid",$user,PDO::PARAM_STR);
		$stmt->execute();
		
		if($stmt){ echo 1; }
		}
		
		