<?php

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

	$userid = intval($_SESSION['user_login']);
	
		
		//get user info
		$stmt="SELECT * FROM users WHERE userid = :userid";
		$stmt=$pdo->prepare($stmt);
		$stmt->bindParam("userid", $userid, PDO::PARAM_STR);
		$stmt->execute();
		$userVal=$stmt->fetch();
		
		
		//Get Account User Balance
		$stmt="SELECT * FROM account WHERE userid = :userid";
		$stmt=$pdo->prepare($stmt);
		$stmt->bindParam("userid", $userid, PDO::PARAM_STR);
		$stmt->execute();
		$balance=$stmt->fetch();
		
		
		
		// get Admin info
		$stmt=$pdo->prepare("SELECT * FROM users WHERE type='admin' ");
		$stmt->execute();
		$adminInfo=$stmt->fetch();
		
		
		
		
		
		
	

	
//UPDATE PROFILE IMAGE

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 USER 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>";
	}
	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",$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>
			
			
			';
		}
		}
		
		}
		
		
		
		
		
		
		
		
		
		

	//CONTACT US - SEND MESSAGE TO ADMIN

	if(isset($_POST["contactUs"])){
		
		//Get Admin ID
		$stmt=$pdo->prepare("SELECT userid FROM users WHERE type='admin' ");
		$stmt->execute();
		$admin=$stmt->fetch();


	$adminID = intval($admin["userid"]);
	$message = htmlspecialchars(str_ireplace('  ','',$_POST["message"]));
	$status = "unread";
	

	
	
	if($message =="" || $message ==" " || $message =="   " || empty($message)){
		$error[] = "<br>Please enter your contact message<br><script>$('#messages').focus()</script>";
	}
	elseif(strlen($message) < 20){
		 $error[] = "<br>Message too short<br>Enter a minimum of 20 characters<br><script>$('#messages').focus()</script>";
	  }
	  
	 	
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{
		$stmt = $pdo->prepare("INSERT INTO contact (userid, message, status, receiver) VALUES (:userid,:message,:status,:receiver)");
		
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->bindParam(":message",$message,PDO::PARAM_STR);
		$stmt->bindParam(":status",$status,PDO::PARAM_STR);
		$stmt->bindParam(":receiver",$adminID,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//Fade Out Form
			
				$("#contactForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Message Sent");
					
				});	
			</script>
			
			
			';
		}
		}
		
		}		
		
		
		
		
		
		
		
		

	//WITHRAWAL REQUEST

	if(isset($_POST["withdrawal"])){
			
	$password = htmlspecialchars($_POST["password"]);
	$ref = htmlspecialchars($_POST["widRef"]);
	$amount = htmlspecialchars($_POST["amount"]);
	$btc = htmlspecialchars($_POST["btc"]);
	$ethereum = htmlspecialchars($_POST["ethereum"]);
	$usdt = htmlspecialchars($_POST["usdt"]);
	$usdc = htmlspecialchars($_POST["usdc"]);
	$walletType = htmlspecialchars($_POST["walletType"]);
	
	
	
	//Validate wallet Address
	if(empty($btc) AND empty($ethereum) AND empty($usdt) AND empty($usdc)){
		$error[] = "<br>Provide a wallet address (BTC or ETH or USDT or usdc)<br>";
	}
	 

	//Validate Checkbox withdrawal option
	elseif(empty($walletType)){
		 $error[] = "<br>Select withdrawal method <br>";
	  }
	  
	 //check selected withdrawal method and validate
	 elseif($walletType == "Bitcoin" AND empty($btc)){
		 $error[] = "<br>Enter your BTC wallet address <br><script>$('#btc').focus()</script>";
	 }
	 elseif($walletType == "Ethereum Bep20" AND empty($ethereum)){
		 $error[] = "<br>Enter your Ethereum Bep20 address <br><script>$('#ethereum').focus()</script>";
	 }
	 elseif($walletType == "Tether USDT(TRC20)" AND empty($usdt)){
		 $error[] = "<br>Enter your Tether USDT(TRC20) address <br><script>$('#usdt').focus()</script>";
	 }
	 elseif($walletType == "Tether USDC(SOL)" AND empty($usdc)){
		 $error[] = "<br>Enter your Tether USDC(sol) address <br><script>$('#usdc').focus()</script>";
	 }
	
	
	 //Validate Amount
	  elseif(empty($amount)){
		 $error[] = "<br>Enter withdrawal amount<br><script>$('#amount').focus()</script>";
	  }
	  elseif($amount < 50){
		 $error[] = "<br>The minimum withdrawal amount is $50 <br><script>$('#amount').focus()</script>";
	  }
	  
	  elseif($amount > $balance["balance"]){
		   $error[] = "<br>Your balance is insufficient - $ ".$balance["balance"]." <br><script>$('#amount').focus()</script>";
	  }
	  
	  
	  
	 
	 //validate user password
	$passwordCheck = password_verify($password, $userVal["password"]);
	
	if(empty($password)){
		$error[] = "<br>Enter your password<br><script>$('#password').focus()</script>";
	}
	elseif($password != $passwordCheck){
		$error[] = "<br>Access Denied. Wrong password<br><script>$('#password').focus()</script>";
	}
	
	
	  
	 
	  
	 	
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{
			
		$type = "withdrawal";
		$status = "pending";
		$stmt = $pdo->prepare("INSERT INTO transactions (userid, amount, ref, type, status, walletType) 
								VALUES (:userid, :amount, :ref, :type, :status, :walletType)");
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->bindParam(":amount",$amount,PDO::PARAM_STR);
		$stmt->bindParam(":ref",$ref,PDO::PARAM_STR);
		$stmt->bindParam(":type",$type,PDO::PARAM_STR);
		$stmt->bindParam(":status",$status,PDO::PARAM_STR);
		$stmt->bindParam(":walletType",$walletType,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			echo '
			<script>
			//Fade Out Form
			
				$("#withdrawalForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Pending");
					
				});	
			</script>';
			
			
			
			//Send Confirmation Email to user
			require_once("../mails/withdrawal_pending.php");
			
			
		}
		}
		
		}		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		

	//INVEST
	
	

	if(isset($_POST["ref"])){
		
	$ref = htmlspecialchars($_POST["ref"]);
	
	
	if(empty($_POST["amount"])){
		$amount = htmlspecialchars($_POST["customAmount"]);
	}else{
		$amount = htmlspecialchars($_POST["amount"]);
	}
	
	
	if(!preg_match('/^[0-9]+$/',$amount)){
		 $error[] = "<br>Enter a valid amount<br><script>$('#amount').focus()</script>";
	  }
	  
	elseif($amount < 50){
		 $error[] = "<br>Enter amount from $50<br><script>$('#amount').focus()</script>";
	  }
	elseif($amount > 100000){
		 $error[] = "<br>Maximum amount per deposit $100,000<br><script>$('#amount').focus()</script>";
	  }
	
	

	 //$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;
	  }
	  
	  
	  
	  
	  
	  
	 
		if(isset($error)){
		foreach($error as $errors){
			echo $errors;
		}
		}else{
			
		$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",$userid,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>
			//Fade Out Form
			
				$("#contactForm").slideUp(function(){
					$("#suc").removeClass("display-none").fadeIn("slow");
					$("#wlcm").html("Request Submitted");
					$("#amt").html("<b>Payable Amount:</b> $ '.number_format($amount).'.00");
					$("#refss").html("<b>Ref:</b> '.$ref.'");
					$("#note").html("Complete payment with the wallet address");
					$("#plan").html("'.$plan.'");
					
				});	
			</script>';
			
			
			
			//Send Confirmation Email to user
			require_once("../mails/pending_Invetment.php");
			
			
		}
		}
		
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	
	///UPDATE PASSWORD
		
	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>';
			
			
			
			
			//Send Confirmation Email to user
			require_once("../mails/change_password.php");
			
			
		}
			
			}catch(PDOException $e){
				echo "Error occured " . $e->getMessage();
			}
				
			}
		
		
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		//UPADATE Notification as read
			
			if(isset($_POST["msgId"])){
				
			$id = intval($_POST["msgId"]);
			
			$stmt = $pdo->prepare("UPDATE contact SET status='read' WHERE id=:id");
			$stmt->bindParam(":id",$id,PDO::PARAM_STR);
			$stmt->execute();

			}
			
			
		
		
		
		
		
		
		
	//REDEEM MONEY TO ACCOUNT

	if(isset($_POST["redeem"])){
		
	$profit = intval($balance["profits"]);
	$balance = intval($balance["balance"]);
	
	//check if profit is > 0
	if($profit > 0){
		
		$newBalance = $profit + $balance;
		$newprofit = 0;
		$dateTime = date("y-m-d h:i:s");
		
		$stmt = $pdo->prepare("UPDATE account SET profits=:profits, balance=:balance, dateTime=:dateTime WHERE userid=:userid");
		$stmt->bindParam(":userid",$userid,PDO::PARAM_STR);
		$stmt->bindParam(":profits",$newprofit,PDO::PARAM_STR);
		$stmt->bindParam(":balance",$newBalance,PDO::PARAM_STR);
		$stmt->bindParam(":dateTime",$dateTime,PDO::PARAM_STR);
		$stmt->execute();
		if($stmt){
			
			echo '
			<span style=color:green>Redeemed Successful <i class="fas fa-check"></i></span>
			<script>
			$("#bals").html("$ " +'.$newBalance.');
			$("#prof").html("$ " +'.$newprofit.');
			</script>';
		}
		
		}else{
			echo "<span style='color:#ff5b5b;'>Insufficient fund</span>";
		}
		
	
		
		}
		
		
		
		
		
		