<?php session_start();?>

<?php
error_reporting(0);
date_default_timezone_set("Asia/Kuala_Lumpur");
include_once("Connect.php");
?>

<?php
/*?>$originalDate = $_POST['Tarikh_daftar'];
$Tarikh_daftar = date("Y-m-d", strtotime($originalDate));<?php */
//$product_wallet = number_format($product_wallet_1,2);
?>


<?php
function randomRefferalCode()
{
	$alphabet    = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
	$pass        = array(); //remember to declare $pass as an array
	$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
	for ($i = 0; $i < 8; $i++) {
	$n      = rand(0, $alphaLength);
	$pass[] = $alphabet[$n];
	}
	return implode($pass); //turn the array into a string
}


function randomRefferalNumber()
{
	$alphabet    = "0123456789";
	$pass        = array(); //remember to declare $pass as an array
	$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
	for ($i = 0; $i < 6; $i++) {
	$n      = rand(0, $alphaLength);
	$pass[] = $alphabet[$n];
	}
	return implode($pass); //turn the array into a string
}
?>

<?php
session_start();
if (isset($_POST['login'])) 
{   
    $email  = htmlspecialchars($_POST['email'], ENT_QUOTES);
    $password  = htmlspecialchars($_POST['password'], ENT_QUOTES);
	$username  = htmlspecialchars($_POST['username'], ENT_QUOTES);

	$from_what_internet = $_POST['from_what_internet'];
	 
	$page = 'https://mygoldsdnbhd.com/log-masuk/' ;

	$sql = "SELECT * FROM user 
	WHERE email ='$email' 
	AND nick_name='$username'
	AND password='$password'
	And status ='1'";
	$result = $mysqli->query($sql);
    if ($result->num_rows > 0)
    {
        $row = $result->fetch_assoc();
		$status = $row['status'];
		$level = $row['level'];

		if ($level != '1')
		{
			$sql_login_status = "SELECT * 
			FROM system_setting 
			LIMIT 1";
			$result_login_status = $mysqli->query($sql_login_status);
			$row_login_status = $result_login_status->fetch_assoc();
			$login_status = $row_login_status['login_status'];		
			if ($login_status == '0')
			{
				//echo "<script type='text/javascript'>alert('System under daily maintenance from 12AM - 6AM. Please login after 6AM. Thank You');</script>";
				echo "<script type='text/javascript'>alert('System under monthly maintenance. Please login later. Thank You');</script>";
				echo "<script type='text/javascript'> document.location='$page'; </script>";
				exit();
			}
		}

		if ( $status == '0')
		{
			echo "<script type='text/javascript'>alert('Sorry. Your Account not being active yet.Please go to your email and verified it before login');</script>";
			echo "<script type='text/javascript'> document.location='$page&error_code=0'; </script>";
			exit();

		}		
		else
		if ( $status == '9')
		{
			echo "<script type='text/javascript'>alert('Sorry. Your Account has been suspended');</script>";
			echo "<script type='text/javascript'> document.location='$page&error_code=9'; </script>";
			exit();
		}
		else 
		if ( $status == '1')
		{
			$ref_code = $row['ref_code'];
			$_SESSION['id']       = $row['id'];
			$_SESSION['ref_code'] = $row['ref_code'];
			$_SESSION['level']    = $row['level'];
			$_SESSION['rank']    = $row['rank'];
			$_SESSION['nick_name']    = $row['nick_name'];
			$_SESSION['email']    = $row['email'];
			$_SESSION['name']     = $row['name'];
			$_SESSION['phone_number']   = $row['phone_number'];
			$_SESSION['profile_image']   = $row['profile_image'];
			$_SESSION['type_of_user']   = $row['type_of_user'];	
			$_SESSION['activation_status']   = $row['activation_status'];	

			if ($_SESSION['level'] == '1') 
			{
				echo "<script type='text/javascript'> document.location='../U/admin_main_dashboard.php'; </script>";
				//echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/maintenance/'; </script>";
				exit();
			}
			else 
			if ($_SESSION['level'] == '2') 
			{
				echo "<script type='text/javascript'> document.location='../U/user_main_dashboard.php'; </script>";
				//echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/maintenance/'; </script>";
				exit();
			}
		}      
	} 
	else
	{
	    echo "<script type='text/javascript'>alert('Wrong Email/Username Or Password. Please try again');</script>";
		echo "<script type='text/javascript'> document.location='$page'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['web_registration'])) 
{
	$sponsor_code = htmlspecialchars($_POST['sponsor_code'],ENT_QUOTES);		
	$name = htmlspecialchars($_POST['name'],ENT_QUOTES);
	$countryCode = htmlspecialchars($_POST['countryCode'],ENT_QUOTES);
	$phone_number = htmlspecialchars($_POST['phone_number'],ENT_QUOTES);
	$email = htmlspecialchars($_POST['email'],ENT_QUOTES);	
	$nick_name = htmlspecialchars($_POST['nick_name'],ENT_QUOTES);
	$password = htmlspecialchars($_POST['password'],ENT_QUOTES);
	$password_retype = htmlspecialchars($_POST['password_retype'],ENT_QUOTES);
	$send_verification = htmlspecialchars($_POST['send_verification'],ENT_QUOTES);
	$amount = htmlspecialchars($_POST['amount'],ENT_QUOTES);
	$package_ref_code = htmlspecialchars($_POST['package_ref_code'],ENT_QUOTES);

	$registration_payment_status = '1';
	$registration_fee = $amount;
	$sql_registration_setting = "SELECT registration_fee, registration_payment_status
								 FROM system_setting
								 WHERE status='1'
								 ORDER BY id DESC
								 LIMIT 1";
	$result_registration_setting = $mysqli->query($sql_registration_setting);
	if ($result_registration_setting && $result_registration_setting->num_rows > 0)
	{
		$row_registration_setting = $result_registration_setting->fetch_assoc();
		$registration_payment_status = $row_registration_setting['registration_payment_status'] ?? '1';
		$registration_fee = $row_registration_setting['registration_fee'] ?? $amount;
	}

	if ($registration_payment_status == '1')
	{
		$amount = $registration_fee;
	}
	else
	{
		$amount = '0';
	}

	if ($email == "") 
	{
		$email = $nick_name . "@gmail.com";
	}

	$firstCharacter = substr($phone_number, 0, 1);
	if ($firstCharacter == "0")
	{
	    $phone_number = substr($phone_number,1);
	}

	$phone_number = $countryCode.$phone_number;

	if ($send_verification == "SMS")
	{
	    $send_to_sms = "1";
	}
	else
	if ($send_verification == "Email")
	{
	    $send_to_email = "1";
	}
	else
	if ($send_verification == "SMS_Email")
	{
	    $send_to_sms = "1";
		$send_to_email = "1";
	}


	if ( $sponsor_code == '')
	{
	     $sponsor_code = "DuniaTiket";  
	}
	
	$from_web = $_POST['from_web'];
	if ( $from_web == 'System')			
	{
		$page_success = "../U/add_new_user.php";
		$page_fail = "../U/add_new_user.php";
	}
	else
	{
		$page_success = "https://mygoldsdnbhd.com/pendaftaran/";
		$page_fail = "https://mygoldsdnbhd.com/pendaftaran/";
	}

	if ( $password == '') 
	{
		echo "<script type='text/javascript'>alert('Fail.Error with password');</script>";
        echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}
	else
	if ( $password != $password_retype) 
	{
		echo "<script type='text/javascript'>alert('Fail.Please make sure your Password and Retype Password id same');</script>";
        echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}
	
	//Check Sponsor Detail
	$sql_check_sponsor_detail = "SELECT * FROM user 
	WHERE nick_name='$sponsor_code'
	AND status = '1'";
	$result_check_sponsor_detail = $mysqli->query($sql_check_sponsor_detail);
	if ($result_check_sponsor_detail -> num_rows > 0)
	{
		$row_check_sponsor_detail = $result_check_sponsor_detail -> fetch_assoc();
		$sponsor_id = $row_check_sponsor_detail['user_id'];
	    $sponsor_ref_code = $row_check_sponsor_detail['ref_code'];
	    $sponsor_email = $row_check_sponsor_detail['email'];
	    $sponsor_name = $row_check_sponsor_detail['name'];
	    $placement_no_of_downline = $row_check_sponsor_detail['no_of_downline'];
	}
	else
	{
	  echo "<script type='text/javascript'>alert('This Sponsor ID not exist.Please try again');</script>";
      echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
      exit();
	}

	if ($sponsor_ref_code == '') 
	{
		echo "<script type='text/javascript'>alert('Fail. Please input the right Sponsor Referral ID');</script>";
		echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}

	//Check existing email
    $sql_check_email = "SELECT * 
    FROM user 
	WHERE email='$email'
	AND status = '1'
	LIMIT 1";
	$result_check_email = $mysqli-> query($sql_check_email);
	if ($result_check_email -> num_rows > 0)
	{
		echo "<script type='text/javascript'>alert('This email already being registered before. Please use other email');</script>";
        echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}

	$cash_wallet = 0 ;
	$product_wallet = 0 ;
	$capital_wallet = 0 ;
	$status = 1 ;
	$level  = 2 ; 
        
	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$word = "Success Registration.Please check your email in 24 hours for registration detail";	

	$New_ref_code = randomRefferalCode();
	$trans_code = randomRefferalCode();

	$mysqli->begin_transaction();

	//Check Sponsor Detail
	$sql_find_placement = "SELECT * FROM user
	WHERE nick_name='$sponsor_code'
	And status='1'
	LIMIT 1";	
	$result_find_placement = $mysqli-> query($sql_find_placement);
	if ($result_find_placement -> num_rows > 0)
	{
		$row_find_placement = $result_find_placement ->fetch_assoc();
		$placement_code = $row_find_placement['ref_code'];
		$placement_ref_code = $row_find_placement['ref_code'];
		$placement_email = $row_find_placement['email'];
		$placement_name = $row_find_placement['name'];
		$placement_no_of_downline = $row_find_placement['no_of_downline'];
	}

	$placement_new_no_of_downline = $placement_no_of_downline + 1 ; //Tambah 1 dekat no of downline placement
	
	$sponsor_id = $sponsor_id;
	$client_ip = getClientIp();
    $country_static = getCountryFromIp($client_ip);

	//Insert downline detail into User table
	$query_user  = " INSERT INTO user
	(
	level,	
	ref_code,
	nick_name,
	sponsor_id, 
	sponsor_code,
	email,
	password,
	name,
	phone_number,
    country_static,
	activation_status,
    verification_status,
	status,
	created_date
	)
	VALUES
	(
	'$level',
	'$New_ref_code',
	'$nick_name',
	'$sponsor_id',
	'$sponsor_ref_code',
	'$email',
	'$password',
	'$name',
	'$phone_number',
    '$country_static',
	'0',
	'0',
    '0',
	'$created_date'
	)";
	$res_user = $mysqli->query($query_user);
	
	//Insert downline wallet detail into wallet table
	$query_wallet  = " INSERT INTO wallet
	(
	ref_code,	
	cash_wallet,
	product_wallet,
	pins_wallet,
	status,
	created_date
	)
	VALUES
	(
	'$New_ref_code',
	'$cash_wallet',
	'$product_wallet',
	'$capital_wallet',
	'0',
	'$created_date'
	)";
	$res_wallet = $mysqli->query($query_wallet);
	
	if ($res_user && $res_wallet) 
	{
		$mysqli->commit();

		if ($registration_payment_status == '1')
		{
			echo "<script type='text/javascript'>window.location.href='../U/checkout_proceed_B_registration_package_toyyibpay.php?user_ref_code=$New_ref_code&trans_code=$trans_code&package_ref_code=$package_ref_code&amount=$amount';</script>";
			exit();
		}

		echo "<script type='text/javascript'>window.location.href='../U/Form-Verification.php?ref_code=$New_ref_code';</script>";
		exit();

		if ($send_to_email == '1')
		{
			/********************** Email To User *************************************************/
			$to = $email;
			$subject = "Hi $name mygoldsdnbhd.com Account Verification";
        
			$message = "
			<html>
			<head>
			<title>Hi $name, mygoldsdnbhd.com Account Verification</title>
			</head>
			<body>
			<p>

			Hai $name,<br><br>

			Thank you for your registration with mygoldsdnbhd.com<br><br>

			This is your registration info :<br><br>

			Full Name : ".$name."<br>
			Email : ".$email."<br>
			Password : ".$password."<br>
			</p>

			</body>
			</html>
			";
        
			$headers  = "MIME-Version: 1.0\r\n";
			$headers .= "Content-type:text/html;charset=UTF-8\r\n";
			$headers .= "From: mygoldsdnbhd.com <no-reply@mygoldsdnbhd.com>\r\n";
			$headers .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";

			$sent = mail($to, $subject, $message, $headers);

			if (!$sent) 
			{
				echo "<script>alert('Email failed to send (server mail()). Please contact admin.');</script>";
			}
			/********************** Email To User *************************************************/
		}
		
		if ($send_to_sms == '1')
		{
			/********************** SMS To User Start*************************************************/
			$message = "RM0 UMRAH HAJI MABRUR SDN BHD: Activation Link: https://system.mygoldsdnbhd.com/System/Page/U/Form-Verification.php?ref_code=".$New_ref_code;

			$curl = curl_init();
			$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
			$params = array(
			'username' => 'mygoldplt_websystemmabrur',
			'password' => 'mygoldplt_websystemmabrur123',
			'message' => $message,
			'mobile' => $phone_number,
			'Sender' => 'Test',
			'type' => '1'
			);
			$url = $endpoint . '?' . http_build_query($params);
			curl_setopt($curl, CURLOPT_URL, $url);

			$result = curl_exec($curl);
			$info = curl_getinfo($curl);  
			curl_close($curl);
			$obj = json_decode($result);

			//echo "<script type='text/javascript'>alert('$result);</script>";
			/********************** SMS To User End*************************************************/
		}
		
		if ($send_to_email == '1' &&  $send_to_sms == '1')
		{
		   echo "<script type='text/javascript'>alert('Verification email to $email & sms to $phone_number has been sent.');</script>";
		}
		else
		if ($send_to_email == '1' )
		{
		   echo "<script type='text/javascript'> document.location='../U/Form-Verification.php?ref_code=$New_ref_code'; </script>";
		   //echo "<script type='text/javascript'>alert('Verification email has been sent to $email. Please check both inbox and spam folder');</script>";
		}
		else
		if ($send_to_sms == '1' )
		{
		   echo "<script type='text/javascript'>alert('Verification sms has been sent to $phone_number.');</script>";
		}

		
		echo "<script type='text/javascript'> document.location='$page_success'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail');</script>";
		echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	} 
}
?>


<?php
if (isset($_POST['activate_new_user'])) 
{
	$from_page = $_POST['from_page'];
	$ref_code = $_POST['ref_code'];
	$activation_way = $_POST['activation_way'];
	$activation_charge = $_POST['activation_charge'];

	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$today = date('Y-m-d');

	if ($from_page == "user_detail.php")
	{
	    $page_success = "user_detail.php?user_ref_code=".$ref_code;
		$page_fail = "user_detail.php?user_ref_code=".$ref_code;
	}
	else
	if ($from_page == "activate_account.php")
	{
	   $page_success = "user_dashboard.php";
	   $page_fail = "activate_account.php";
	}
	else
	if ($from_page == "user_main_dashboard.php")
	{
	   $page_success = "user_main_dashboard.php";
	   $page_fail = "user_main_dashboard.php";
	}

	$sql_repeat_activate = "SELECT * 
	FROM transactions 
	WHERE user_ref_code = '$ref_code'
	AND type_of_process = 'Member Activate Account'
	AND status = '1'
	AND created_date = '$today'";
	$result_repeat_activate = $mysqli-> query($sql_repeat_activate);
	if ($result_repeat_activate -> num_rows > 0)
	{
		echo "<script type='text/javascript'>alert('Your Account Already Activated.');</script>";
		echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/'; </script>";
		exit();
	}

	$sql_user = "SELECT * FROM user 
	WHERE ref_code='$ref_code'
	And status='1'";
	$result_user = $mysqli-> query($sql_user);
	if ($result_user -> num_rows > 0)
	{
		$row_user = $result_user ->fetch_assoc();
		$id = $row_user['id'];
		$ref_code = $row_user['ref_code'];
		$name = $row_user['name'];
		$last_name = $row_user['last_name'];
		$email = $row_user['email'];
		$password = $row_user['password'];
	}

	//Check Registration Price
	$sql_reg_price = "SELECT *
					  FROM registration_price_setting
					  Where status='1'
					  order by id Asc";
					  $result_reg_price = $mysqli-> query($sql_reg_price);
	if ($result_reg_price -> num_rows > 0)
	{
		$row_reg_price = $result_reg_price ->fetch_assoc();
		$full_total_price = $row_reg_price['price'];
	}

	if ($activation_charge == "Free")
	{
	    $full_total_price = 0;
	}

	/********************************************************** Member Transaction Part Start Here *******************************/
	//Members Wallet
    $sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_product_wallet = $row_my_wallet['product_wallet'];
	}

	$my_new_wallet = $my_product_wallet - $full_total_price;

	if ($my_new_wallet < 0)
	{
	    echo "<script type='text/javascript'>alert('Fail. User Activation Wallet Balance is Insufficient');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page_fail'; </script>";
		exit();
	}

	$mysqli->begin_transaction();
	
	//Update member wallet
	$Update_my_wallet = "UPDATE wallet SET   
	product_wallet ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	$trans_code = randomRefferalCode();

	$type_of_transaction = "PW";
	$status = 1;
	$activation_status = 0;
	$in_transactions = 0;
	$out_transactions = $full_total_price ;
	$description = "Activate Account $full_total_price " ;
	$type_of_transaction = $type_of_transaction ;
	$type_of_process = "Member Activate Account";

	//Insert Deposit Transactions
	$query_activation  = " INSERT INTO transactions
	(
	user_ref_code,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	description,
	activation_status,
	status,
	created_date
	)
	VALUES
	(
	'$ref_code',
	'$trans_code',
	'$type_of_process',
	'$type_of_transaction',
	'$in_transactions',
	'$out_transactions',
	'$description',
	'$activation_status',
	'$status',
	'$created_date'
	)";
	$res_activation = $mysqli->query($query_activation);

	/********************************************************** Member Transaction Part End Here *******************************/

	/********************************************************** HQ Transaction Part Start Here *******************************/
	//HQ Wallet
	$hq_ref_code = "MGP10000";

	$sql_hq_wallet = "SELECT * FROM wallet
	WHERE ref_code='$hq_ref_code' LIMIT 1";
	$result_hq_wallet = $mysqli-> query($sql_hq_wallet);
	if ($result_hq_wallet -> num_rows > 0)
	{
		$row_hq_wallet = $result_hq_wallet ->fetch_assoc();
		$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
	}

	$hq_new_wallet = $hq_cash_wallet + $full_total_price;

	//Update HQ wallet
	$Update_hq_wallet = "UPDATE wallet SET   
	cash_wallet ='$hq_new_wallet'
	WHERE ref_code ='$hq_ref_code'";
	$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

	$type_of_transaction = "CW";
	$hq_ref_code = "MGP10000";
	$status_hq = '1';
	$in_transactions_hq = $full_total_price;
	$out_transactions_hq = 0 ;
	$description_hq = "Activation Fees $full_total_price " ;
	$type_of_transaction_hq = $type_of_transaction ;
	$type_of_process_hq = "HQ Activation Fees";

	//HQ activation fees
	$query_hq_activation_charge  = " INSERT INTO transactions
	(
	user_ref_code,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$hq_ref_code',
	'$trans_code',
	'$type_of_process_hq',
	'$type_of_transaction_hq',
	'$in_transactions_hq',
	'$out_transactions_hq',
	'$description_hq',
	'$status_hq',
	'$created_date'
	)";
	$res_hq_activation_charge = $mysqli->query($query_hq_activation_charge);

	/********************************************************** HQ Transaction Part End Here *******************************/

	$Update_User_Detail = "UPDATE user SET  
	activation_status ='1'
	WHERE ref_code ='$ref_code'";
	$resUpdate_User_Detail = $mysqli->query($Update_User_Detail);

	if ($resUpdate_my_wallet && $res_activation && $resUpdate_hq_wallet && $res_hq_activation_charge && $resUpdate_User_Detail) 
	{
		$mysqli->commit();
		echo "<script type='text/javascript'> document.location='../U/activate_account_process.php?trans_code=$trans_code&activation_charge=$activation_charge&from_page=$from_page'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page_fail'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['verified_new_user'])) 
{
	$from_page = $_POST['from_page'];
	$ref_code = $_POST['ref_code'];
	$activation_way = $_POST['activation_way'];

	if ($from_page == "user_detail.php")
	{
	    $page_success = "user_detail.php?user_ref_code=".$ref_code;
		$page_fail = "user_detail.php?user_ref_code=".$ref_code;
	}
	else
	if ($from_page == "activate_account.php")
	{
	   $page_success = "user_dashboard.php";
	   $page_fail = "activate_account.php";
	}

	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d');

	$sql_user = "SELECT * FROM user 
	WHERE ref_code='$ref_code'
	And status='1'";
	$result_user = $mysqli-> query($sql_user);
	if ($result_user -> num_rows > 0)
	{
		$row_user = $result_user ->fetch_assoc();
		$id = $row_user['id'];
		$ref_code = $row_user['ref_code'];
		$name = $row_user['name'];
		$last_name = $row_user['last_name'];
		$email = $row_user['email'];
		$password = $row_user['password'];
	}

	$Update_User_Detail = "UPDATE user SET  
	verification_status ='1',
	activation_status ='1'
	WHERE ref_code ='$ref_code'";
	$resUpdate_User_Detail = $mysqli->query($Update_User_Detail);

	if ($resUpdate_User_Detail) 
	{
		$mysqli->commit();

		/********************** Email To User *************************************************/
		$to = $email;
		$subject = "Hi $email, mygoldsdnbhd.com Account Verification";
        
		$message = "
		<html>
		<head>
		<title>Hi $email, mygoldsdnbhd.com Account Verification</title>
		</head>
		<body>
		<p>

		Hai $email,<br><br>

		Your account has been verified. You can proceed with your withdrawal request  <br><br>
		</p>

		</body>
		</html>
		";
        
		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
		// More headers
		$headers .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
		$headers .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
		$headers .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
		mail($to, $subject, $message, $headers);
		/********************** Email To User *************************************************/


        echo "<script type='text/javascript'>alert('Succesfully Verified Member');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page_fail'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page_fail'; </script>";
		exit();
	}
}
?>



<?php
if (isset($_POST['reject_verificaion_new_user'])) 
{
	$from_page = $_POST['from_page'];
	$ref_code = $_POST['ref_code'];
	$rejection_message  = htmlspecialchars($_POST['rejection_message'], ENT_QUOTES);

	if ($from_page == "user_detail.php")
	{
	    $page_success = "user_detail.php?user_ref_code=".$ref_code;
		$page_fail = "user_detail.php?user_ref_code=".$ref_code;
	}
	else
	if ($from_page == "activate_account.php")
	{
	   $page_success = "user_dashboard.php";
	   $page_fail = "activate_account.php";
	}

	$sql_user = "SELECT * FROM user 
	WHERE ref_code='$ref_code'
	And status='1'";
	$result_user = $mysqli-> query($sql_user);
	if ($result_user -> num_rows > 0)
	{
		$row_user = $result_user ->fetch_assoc();
		$id = $row_user['id'];
		$ref_code = $row_user['ref_code'];
		$name = $row_user['name'];
		$last_name = $row_user['last_name'];
		$email = $row_user['email'];
		$password = $row_user['password'];
	}

	/********************** Email To User *************************************************/
	$to = $email;
	$subject = "Hi $email, mygoldsdnbhd.com Account Verification Rejection";
        
	$message = "
	<html>
	<head>
	<title>Hi $email, mygoldsdnbhd.com Account Verification Rejection</title>
	</head>
	<body>
	<p>

	Hai $email,<br><br>

	Your account verification has been rejected because of issue below. <br><br>

	Issue: $rejection_message <br>
	</p>

	</body>
	</html>
	";
        
	// Always set content-type when sending HTML email
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
	// More headers
	$headers .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
	$headers .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
	$headers .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
	mail($to, $subject, $message, $headers);
	/********************** Email To User *************************************************/

    echo "<script type='text/javascript'>alert('Rejection Of Verification Email Sent');</script>";
	echo "<script type='text/javascript'> document.location='../U/$page_fail'; </script>";
	exit();
}
?>


<?php
if (isset($_POST['Add_Attachment'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$title = htmlspecialchars($_POST['title'], ENT_QUOTES);

	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d');
	$status = '1';
	$attachment_ref_code = randomRefferalCode();

   	$mysqli->begin_transaction();

	if ($_FILES['file_attach']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["file_attach"]["name"]);
		$newfilename1 = $attachment_ref_code . $time_stamp. '.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{

			$check1 = getimagesize($_FILES["file_attach"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["file_attach"]["tmp_name"], $target_file1)  )
			{
				$file_attach = $attachment_ref_code . $time_stamp. '.' . end($temp1);

				$query  = " INSERT INTO my_attachment
				(
				title,
				file_attach,
				status, 
				created_date
				)
				VALUES
				(
				'$title',
				'$file_attach',
				'$status', 
				'$created_date'
				)";		
				$result = $mysqli->query($query);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
				exit();
			}
		}
	}
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Upload');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}     
}
?>

<?php
if (isset($_POST['Update_Attachment'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$title = htmlspecialchars($_POST['title'], ENT_QUOTES);

	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d');
	$status = '1';
	$attachment_ref_code = randomRefferalCode();

   	$mysqli->begin_transaction();

	if ($_FILES['file_attach']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["file_attach"]["name"]);
		$newfilename1 = $attachment_ref_code . $time_stamp. '.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{

			$check1 = getimagesize($_FILES["file_attach"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["file_attach"]["tmp_name"], $target_file1)  )
			{
				$file_attach = $attachment_ref_code . $time_stamp. '.' . end($temp1);

				$UpdateQuery = "UPDATE my_attachment SET 
				title='$title',
				file_attach='$file_attach'
				WHERE id='$id' ";
				$result = $mysqli->query($UpdateQuery);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
				exit();
			}
		}
	}
	else 
	{	
		$UpdateQuery = "UPDATE my_attachment SET 
		title='$title'
		WHERE id='$id' ";
		$result = $mysqli->query($UpdateQuery);
    }
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}     
}
?>

<?php
if (isset($_GET['form_name_delete_attachment'])=='delete_attachment') 
{
	$id = $_GET['id'];

	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE my_attachment SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Delete');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/myUHM_attachment.php'; </script>";
	}          
}
?>



<?php
if (isset($_POST['Update_User_Password'])) 
{
	$ref_code  = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
    $current_password  = htmlspecialchars($_POST['current_password'], ENT_QUOTES);
	$new_password  = htmlspecialchars($_POST['new_password'], ENT_QUOTES);
	$retype_new_password  = htmlspecialchars($_POST['retype_new_password'], ENT_QUOTES);

	$sql_user = "SELECT * 
	FROM user 
	WHERE ref_code='$ref_code'";
	$result_user = $mysqli-> query($sql_user);
	if ($result_user -> num_rows > 0)
	{
		$row_user = $result_user ->fetch_assoc();
		$id = $row_user['id'];
		$password = $row_user['password'];
		$security_code = $row_user['security_code'];
	}

	if ($password != $current_password)
	{
	    echo "<script type='text/javascript'>alert('Wrong current password. Please try again');</script>";
		echo "<script type='text/javascript'> document.location='../U/user_password.php?user_ref_code=$ref_code'; </script>";
		exit();
	}

	if ($new_password != $retype_new_password)
	{
	    echo "<script type='text/javascript'>alert('New password not same with reptype password. Please try again');</script>";
		echo "<script type='text/javascript'> document.location='../U/user_password.php?user_ref_code=$ref_code'; </script>";
		exit();
	}

	$mysqli->begin_transaction();

	$Update_User_Password = "UPDATE user SET 
	password ='$new_password'
	WHERE ref_code ='$ref_code'";
	$resUpdate_User_Password = $mysqli->query($Update_User_Password);

	if ($resUpdate_User_Password) 
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Update Password');</script>";
        echo "<script type='text/javascript'> document.location='../U/user_password.php?user_ref_code=$ref_code'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail. Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/user_password.php?user_ref_code=$ref_code'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_GET['form_name_Activate_User'])=='Activate_User') 
{
	$id = $_GET['id'];
	$user_status = $_GET['user_status'];
	$mysqli->begin_transaction();

	$status_approve = '1';
 
	$UpdateQuery= "UPDATE user SET  
	status='$status_approve'
	WHERE id='$id' ";               
	$result_Approve = $mysqli->query($UpdateQuery);

	if($result_Approve)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Activate Member');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?user_status=$user_status'; </script>";		  
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?user_status=$user_status'; </script>";		  
	}     
}

else
if (isset($_GET['form_name_Set_Stokist'])=='Set_Stokist') 
{
	$id = $_GET['id'];

	$mysqli->begin_transaction();

	$status_block = '8';
 
	$UpdateQuery= "UPDATE user SET  
	type_of_user='Stokist'
	WHERE id='$id' ";               
	$result_Stokist = $mysqli->query($UpdateQuery);

	if($result_Stokist)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Set User As Stokist');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php'; </script>";		  
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php'; </script>";		  
	}     
}

else
if (isset($_GET['form_name_Block_Wallet'])=='Block_Wallet') 
{
	$id = $_GET['id'];
	$mysqli->begin_transaction();

	$status_block = '8';
 
	$UpdateQuery= "UPDATE user SET  
	wallet_status='$status_block'
	WHERE id='$id' ";               
	$result_Delete = $mysqli->query($UpdateQuery);

	if($result_Delete)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Block User Wallet');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php'; </script>";		  
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php'; </script>";		  
	}     
}
?>


<?php
if (isset($_POST['Reply_Ticket'])) 
{		
    $user_level = htmlspecialchars($_POST['user_level'], ENT_QUOTES);
	$ref_code = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
	$ticket_id = htmlspecialchars($_POST['ticket_id'], ENT_QUOTES);
	$comment = htmlspecialchars($_POST['comment'], ENT_QUOTES);
 
	$status = 1 ; 
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

	$mysqli->begin_transaction();

	if ($user_level == '1')
	{
		$UpdateQuery= "UPDATE support_ticket SET  
		status ='1'
		WHERE id='$ticket_id' ";               
		$result_reply = $mysqli->query($UpdateQuery);
	}

	$query_support  = "INSERT INTO support_ticket_conversation
	(
	support_ticket_id, 
	user_level,
	ref_code,
	comment,	
	status, 
	created_date
	)
	VALUES
	(
	'$ticket_id', 
	'$user_level',
	'$ref_code',
	'$comment',	
	'$status', 
	'$created_date'
	)";		
	$result_support = $mysqli->query($query_support);

	if($result_support)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'> document.location='../U/ticket_history_detail.php?id=$ticket_id'; </script>";
		exit();
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/ticket_history_detail.php?id=$ticket_id'; </script>";
		exit();
	}
}
?>

<?php
// ===== Commission helpers (copied/adapted from cron_transfer_order_to_db.php) =====
function getPackageCommissionSetting(mysqli $mysqli, string $package_ref_code): array
{
    $package_ref_code = $mysqli->real_escape_string($package_ref_code);

    $sql = "SELECT bonus_sponsor, hibah_unilevel_1, hibah_unilevel_2, hibah_unilevel_3
            FROM package_setting
            WHERE package_ref_code='$package_ref_code'
              AND status='1'
            LIMIT 1";
    $res = $mysqli->query($sql);

    $out = [
        'bonus_sponsor' => 0.0,
        'level_1' => 0.0,
        'level_2' => 0.0,
        'level_3' => 0.0,
    ];

    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $out['bonus_sponsor'] = (float)($row['bonus_sponsor'] ?? 0);
        $out['level_1'] = (float)($row['hibah_unilevel_1'] ?? 0);
        $out['level_2'] = (float)($row['hibah_unilevel_2'] ?? 0);
        $out['level_3'] = (float)($row['hibah_unilevel_3'] ?? 0);
    }

    return $out;
}

function getPackageRefCodeFromOrder(mysqli $mysqli, string $order_id, string $trans_code): string
{
    $order_id = $mysqli->real_escape_string($order_id);

    // do NOT filter by trans_code (because order_item trans_code may be billcode/payment_code)
    $sql = "SELECT item_nilai_mata
            FROM woocommerce_order_info_item
            WHERE order_id='$order_id'
              AND status='1'
            ORDER BY id DESC
            LIMIT 1";
    $res = $mysqli->query($sql);

    if ($res && $res->num_rows > 0) {
        return (string)($res->fetch_assoc()['item_nilai_mata'] ?? '');
    }
    return '';
}

function getSponsorCodeByRefCode($mysqli, string $ref_code): string
{
    $ref_code = $mysqli->real_escape_string($ref_code);
    $res = $mysqli->query("SELECT sponsor_code FROM user WHERE ref_code='$ref_code' AND status='1' LIMIT 1");
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return $row['sponsor_code'] ?? '';
    }
    return '';
}

function agentHasSalesThisMonth($mysqli, string $agent_ref_code): bool
{
    $agent_ref_code = $mysqli->real_escape_string($agent_ref_code);
    $first = date("Y-m-01 00:00:00");
    $last  = date("Y-m-t 23:59:59");

    // 1) Check sales from woocommerce_order_info
    $sql1 = "SELECT id
             FROM woocommerce_order_info
             WHERE status='1'
               AND order_comm_ref_code='$agent_ref_code'
               AND created_date BETWEEN '$first' AND '$last'
             LIMIT 1";
    $res1 = $mysqli->query($sql1);
    if ($res1 && $res1->num_rows > 0) {
        return true;
    }

    // 2) Check commission history from transactions
    $sql2 = "SELECT id
             FROM transactions
             WHERE status='1'
               AND user_ref_code='$agent_ref_code'
               AND created_date BETWEEN '$first' AND '$last'
               AND (
                    type_of_process='bonus_sponsor'
                    OR type_of_process LIKE 'hibah_unilevel_level_%'
               )
             LIMIT 1";
    $res2 = $mysqli->query($sql2);
    if ($res2 && $res2->num_rows > 0) {
        return true;
    }

    return false;
}

function findEligibleAgentCompressed($mysqli, string $candidate_ref_code): string
{
    $maxHop = 30;
    while ($maxHop-- > 0) {
        if ($candidate_ref_code === '' || $candidate_ref_code === 'MGP10000') return '';
        if (agentHasSalesThisMonth($mysqli, $candidate_ref_code)) return $candidate_ref_code;
        $candidate_ref_code = getSponsorCodeByRefCode($mysqli, $candidate_ref_code);
    }
    return '';
}

function addWalletCommission($mysqli, string $agent_ref_code, float $amount, string $trans_code, string $type_of_process, string $description): bool
{
    $amount = (float)$amount;
    if ($amount <= 0) return true;

    $agent_ref_code_esc = $mysqli->real_escape_string($agent_ref_code);
    $trans_code_esc = $mysqli->real_escape_string($trans_code);
    $type_of_process_esc = $mysqli->real_escape_string($type_of_process);
    $description_esc = $mysqli->real_escape_string($description);

    // wallet row
    $resW = $mysqli->query("SELECT cash_wallet FROM wallet WHERE ref_code='$agent_ref_code_esc' LIMIT 1");
    if (!$resW || $resW->num_rows == 0) return false;

    $rowW = $resW->fetch_assoc();
    $current = (float)($rowW['cash_wallet'] ?? 0);
    $newBal = (float)number_format($current + $amount, 2, '.', '');

    // update wallet
    $upd = $mysqli->query("UPDATE wallet SET cash_wallet='$newBal' WHERE ref_code='$agent_ref_code_esc'");
    if ($upd === false) return false;

    // insert transaction (credit)
    $created_date = date('Y-m-d H:i:s');
    $ins = "INSERT INTO transactions
    (
        user_ref_code, trans_code, type_of_process, type_of_transaction,
        in_transactions, out_transactions, balance, description, status, created_date
    )
    VALUES
    (
        '$agent_ref_code_esc', '$trans_code_esc', '$type_of_process_esc', 'In',
        '$amount', '0', '$newBal', '$description_esc', '1', '$created_date'
    )";
    $ok = $mysqli->query($ins);

    return ($ok !== false);
}

function distributeCommissionCompressed(
    mysqli $mysqli,
    string $order_comm_ref_code,   // sponsor ref_code (LEVEL 1)
    float $base_amount_usd,
    string $trans_code,
    int $order_id,
    string $order_item_name,
    array $pkgSetting
): bool
{
    $base_amount_usd = (float)$base_amount_usd;
    if ($base_amount_usd <= 0) return true;

    // =========================
    // LEVEL 1: Bonus Sponsor (direct sponsor)
    // =========================
    $bonusPct = (float)($pkgSetting['bonus_sponsor'] ?? 0);
    if ($bonusPct > 0) {
        $bonusAmt = (float)number_format($base_amount_usd * ($bonusPct / 100.0), 2, '.', '');
        $ok = addWalletCommission(
            $mysqli,
            $order_comm_ref_code,
            $bonusAmt,
            $trans_code,
            'bonus_sponsor',
            "Bonus Sponsor ($bonusPct%) USD $bonusAmt from paid amount USD $base_amount_usd | Order ID: $order_id | $order_item_name"
        );
        if (!$ok) return false;
    }

    // =========================
    // LEVEL 2/3/4: Hibah Unilevel
    // Level 2 -> hibah_unilevel_1
    // Level 3 -> hibah_unilevel_2
    // Level 4 -> hibah_unilevel_3
    // =========================
    $hibahPercents = [
        2 => (float)($pkgSetting['level_1'] ?? 0), // hibah_unilevel_1
        3 => (float)($pkgSetting['level_2'] ?? 0), // hibah_unilevel_2
        4 => (float)($pkgSetting['level_3'] ?? 0), // hibah_unilevel_3
    ];

    // start cursor at LEVEL 1 sponsor
    $cursor = $order_comm_ref_code;

    // For hibah, first receiver is upline 1 (LEVEL 2)
    for ($lvl = 2; $lvl <= 4; $lvl++) {

        // move one level up BEFORE paying hibah (so lvl2 uses sponsor's sponsor)
        $cursor = getSponsorCodeByRefCode($mysqli, $cursor);
        if ($cursor === '' || $cursor === 'MGP10000') break;

        $eligible = findEligibleAgentCompressed($mysqli, $cursor);
        if ($eligible === '') break;

        $pct = (float)($hibahPercents[$lvl] ?? 0);
        if ($pct > 0) {
            $amt = (float)number_format($base_amount_usd * ($pct / 100.0), 2, '.', '');
            $ok = addWalletCommission(
                $mysqli,
                $eligible,
                $amt,
                $trans_code,
                "hibah_unilevel_level_$lvl",
                "Hibah Unilevel L$lvl ($pct%) USD $amt from paid amount USD $base_amount_usd | Order ID: $order_id | $order_item_name"
            );
            if (!$ok) return false;
        }

        // continue chain from compressed eligible
        $cursor = $eligible;
    }

    return true;
}
?>

<?php
if (isset($_POST['Pay_Package'])) 
{
	$ref_code = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
	$order_id = htmlspecialchars($_POST['order_id'], ENT_QUOTES);
	$trans_code = htmlspecialchars($_POST['trans_code'], ENT_QUOTES);
	$full_amount = htmlspecialchars($_POST['full_amount'], ENT_QUOTES);
	$amount = htmlspecialchars($_POST['amount'], ENT_QUOTES);
	$payment_method = htmlspecialchars($_POST['payment_method'], ENT_QUOTES);
	
	$payment_code  = randomRefferalCode();

	$sql_currency = "SELECT deposit_rm FROM currency_rate_setting WHERE status='1' LIMIT 1";
	$result_currency = $mysqli->query($sql_currency);
	$deposit_rm = 1;

	if ($result_currency && $result_currency->num_rows > 0) {
		$deposit_rm = (float)($result_currency->fetch_assoc()['deposit_rm'] ?? 1);
		if ($deposit_rm <= 0) $deposit_rm = 1;
	}

	$min_usd = 50 / (float)$deposit_rm;
	if ((float)$amount < (float)$min_usd) {
		echo "<script>alert('Minimum payment is RM 50 (USD " . number_format($min_usd,2) . ").');</script>";
		echo "<script>document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code';</script>";
		exit();
	}


	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_payment  = "INSERT INTO package_payment
	(
	order_id,
	trans_code,
	payment_code,
	ref_code,
	full_amount,
	amount,
	payment_method,
	status,
	created_date
	)
	VALUES
	(
	'$order_id',
	'$trans_code',
	'$payment_code',
	'$ref_code',
	'$full_amount',
	'$amount',
	'$payment_method',
	'0',
	'$created_date'
	)";
	$res_payment = $mysqli->query($query_payment);	

	if ($payment_method == "E-wallet")
	{	
		$type_wallet = "e_wallet";

		$sql_my_wallet = "SELECT * 
		FROM wallet
		WHERE ref_code='$ref_code' 
		LIMIT 1";
		$result_my_wallet = $mysqli-> query($sql_my_wallet);
		if ($result_my_wallet -> num_rows > 0)
		{
			$row_my_wallet = $result_my_wallet ->fetch_assoc();
			$my_cash_wallet = $row_my_wallet['cash_wallet'];
		}

		if ($type_wallet == 'e_wallet')
		{
			 $my_wallet = $my_cash_wallet;
			 $wallet_column_name ="cash_wallet";
			 $type_of_transaction = "CW";
		}
	
		$my_new_wallet = $my_wallet - $amount;

		if ($my_new_wallet < 0 || $my_new_wallet < 0.00)
		{   
			echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
			echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
			exit();
		}

		if(strpos($my_new_wallet, "-") !== false)
		{
			echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
			echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
			exit();
		}

		$status = 1;
		$in_transactions = 0.00;
		$out_transactions = (float)$amount;
		$description = "Pay Using e-Wallet USD " . number_format((float)$amount, 2);
		$type_of_process = "Pay Package Balance Using Wallet";

		//Payment e-wallet
		$query_payment_ewallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$ref_code',
		'$payment_code',
		'$type_of_process',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$description',
		'$status',
		'$created_date'
		)";
		$res_payment_ewallet = $mysqli->query($query_payment_ewallet);

		$Update_my_wallet = "UPDATE wallet SET
		cash_wallet='$my_new_wallet'
		WHERE ref_code = '$ref_code' ";
		$result_my_wallet = $mysqli->query($Update_my_wallet);

		$sql_order_item = "SELECT *
				   FROM woocommerce_order_info
				   WHERE order_id  = '$order_id'
                   AND trans_code  = '$trans_code'
				   AND status='1'";
		$result_order_item = $mysqli-> query($sql_order_item);
		if ($result_order_item -> num_rows > 0)
		{
			$row_order_item = $result_order_item ->fetch_assoc();
			$order_items  = $row_order_item['order_items'];
			$order_full_total = $row_order_item['order_full_total'];
		}

		$data_total_payment = 
		"SELECT SUM(amount) As num 
		FROM package_payment
		WHERE order_id = '$order_id'
		AND trans_code = '$trans_code'
		AND ref_code = '$ref_code'
		AND status = '1'";    
		$result_total_payment = $mysqli->query($data_total_payment);
		if ($result_total_payment ->num_rows > 0)
		{
			$row_total_payment = $result_total_payment ->fetch_assoc();
			$full_total_payment = $row_total_payment['num'];
		}

		$order_balance = $order_full_total - $full_total_payment - $amount;

		//Update Package Info
		$Update_package_info = "UPDATE package_payment SET
        balance = '$order_balance',
		status='1'
		WHERE payment_code = '$payment_code' ";
		$result_package_info = $mysqli->query($Update_package_info);
	}

	if($res_payment)
	{
		if ($payment_method == "E-wallet")
		{
			if($res_payment && $res_payment_ewallet && $result_my_wallet && $result_package_info)
			{
				// 1) Get sponsor ref_code for this order (order_comm_ref_code)
				$order_comm_ref_code = '';
				$order_items_name = $order_items ?? ("Order Balance Payment");

				$sql_comm = "SELECT order_comm_ref_code, order_items
							 FROM woocommerce_order_info
							 WHERE order_id='$order_id' AND trans_code='$trans_code' AND status='1'
							 LIMIT 1";
				$res_comm = $mysqli->query($sql_comm);
				if ($res_comm && $res_comm->num_rows > 0) {
					$rowc = $res_comm->fetch_assoc();
					$order_comm_ref_code = $rowc['order_comm_ref_code'] ?? '';
					if (!empty($rowc['order_items'])) $order_items_name = $rowc['order_items'];
				}

				// Get package_ref_code (SKU) from order item table
				$package_ref_code = getPackageRefCodeFromOrder($mysqli, $order_id, $trans_code);

				// Read commission % from package_setting
				$pkgSetting = getPackageCommissionSetting($mysqli, $package_ref_code);

				// 2) Run commission based on the paid amount (USD)
				//    IMPORTANT: use $trans_code (order trans_code) so it matches your existing commission records style
				$okCommission = distributeCommissionCompressed(
					$mysqli,
					$order_comm_ref_code,
					(float)$amount,
					$trans_code,
					(int)$order_id,
					"Balance Payment | " . $order_items_name,
					$pkgSetting
				);

				if ($okCommission) 
				{
					$mysqli->commit();
					echo "<script type='text/javascript'>alert('Payment Successful.');</script>";
					echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
				} 
				else 
				{
					$mysqli->rollback();
					echo "<script type='text/javascript'>alert('Fail, Commission Error. Please Try Again');</script>";
					echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
				}
			}
			else
			{
				$mysqli->rollback();
				echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
				echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
			}
		}
		else
		if ($payment_method == "Toyyibpay")
		{
			$mysqli->commit();
			echo "<script type='text/javascript'> document.location='../U/checkout_proceed_B_payment_package_toyyibpay.php?payment_code=$payment_code'; </script>";
		}
		else
		if ($payment_method == "PayPal")
		{
			$mysqli->commit();
			echo "<script type='text/javascript'> document.location='../U/checkout_proceed_B_payment_package_paypal.php?payment_code=$payment_code'; </script>";
		}
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
	}
}
?>

<?php
if (isset($_POST['Purchase_Package'])) 
{
    //$package_ref_code  = htmlspecialchars($_POST['package_ref_code'], ENT_QUOTES);
	
	/*
	$sql_package = "SELECT *
					FROM package_setting
					Where package_ref_code ='$package_ref_code'
					And status='1'
					order by id Asc";
	$result_package = $mysqli-> query($sql_package);
	if ($result_package -> num_rows > 0)
	{
		$row_package = $result_package ->fetch_assoc();
		$package_name = $row_package['package_name'];
		$package_price = $row_package['package_price'];
	}
	*/

	$package_ref_code  = randomRefferalCode();

	$user_id = htmlspecialchars($_POST['user_id'], ENT_QUOTES);

	//Check user info
	$sql_user = "SELECT *
				 FROM user
				 Where id = '$user_id'
				 And status='1'";
	$result_user = $mysqli-> query($sql_user);
	if ($result_user -> num_rows > 0)
	{
		$row_user = $result_user ->fetch_assoc();
		$user_id = $row_user['user_id'];
	}

    $ref_code  = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
	$package_price  = htmlspecialchars($_POST['package_price'], ENT_QUOTES);
	$package_name = "USD ".$package_price;

	$purchase_code = randomRefferalCode();
	$status = 0 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	/********************************************************** Member Transaction Part Start Here *******************************/
	//Members Wallet
    $sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_product_wallet = $row_my_wallet['product_wallet'];
	}

	$my_new_wallet = $my_product_wallet - $package_price;

	if ($my_new_wallet < 0)
	{
	    echo "<script type='text/javascript'>alert('Fail. User Activation Wallet Balance is Insufficient');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_package.php'; </script>";
		exit();
	}

	$mysqli->begin_transaction();
	
	//Update member wallet
	$Update_my_wallet = "UPDATE wallet SET   
	product_wallet ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	$trans_code = randomRefferalCode();

	$type_of_transaction = "PW";
	$status = 1;
	$in_transactions = 0;
	$out_transactions = $package_price ;
	$description = "Purchase New Package $$package_price" ;
	$type_of_transaction = $type_of_transaction ;
	$type_of_process = "Member Purchase New Package";

	//Insert Purchase Transactions
	$query_purchase  = " INSERT INTO transactions
	(
	user_ref_code,
	user_id,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$ref_code',
	'$user_id',
	'$trans_code',
	'$type_of_process',
	'$type_of_transaction',
	'$in_transactions',
	'$out_transactions',
	'$description',
	'$status',
	'$created_date'
	)";
	$res_purchase = $mysqli->query($query_purchase);

	/********************************************************** Member Transaction Part End Here *******************************/

	/********************************************************** HQ Transaction Part Start Here *******************************/
	//HQ Wallet
	$hq_ref_code = "MGP10000";

	$sql_hq_wallet = "SELECT * FROM wallet
	WHERE ref_code='$hq_ref_code' LIMIT 1";
	$result_hq_wallet  = $mysqli-> query($sql_hq_wallet);
	if ($result_hq_wallet  -> num_rows > 0)
	{
		$row_hq_wallet  = $result_hq_wallet  ->fetch_assoc();
		$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
	}

	$hq_new_wallet = $hq_cash_wallet + $package_price;

	//Update HQ wallet
	$Update_hq_wallet = "UPDATE wallet SET   
	cash_wallet ='$hq_new_wallet'
	WHERE ref_code ='$hq_ref_code'";
	$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

	$type_of_transaction = "CW";
	$hq_ref_code = "MGP10000";
	$status_hq = '1';
	$in_transactions_hq = $package_price;
	$out_transactions_hq = 0 ;
	$description_hq = "Member Purchase New Package $package_price " ;
	$type_of_transaction_hq = $type_of_transaction ;
	$type_of_process_hq = "HQ Fees Member Purchase New Package";

	//HQ activation fees
	$query_hq_activation_charge  = " INSERT INTO transactions
	(
	user_ref_code,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$hq_ref_code',
	'$trans_code',
	'$type_of_process_hq',
	'$type_of_transaction_hq',
	'$in_transactions_hq',
	'$out_transactions_hq',
	'$description_hq',
	'$status_hq',
	'$created_date'
	)";
	$res_hq_activation_charge = $mysqli->query($query_hq_activation_charge);

	/********************************************************** HQ Transaction Part End Here *******************************/

	$query_package  = " INSERT INTO package_sale
	(
	purchase_code,
	package_ref_code,
	ref_code,
	user_id,
	package_name,
	package_price,
	status,
	update_id_status,
	created_date
	)
	VALUES
	(
	'$trans_code',
	'$package_ref_code',
	'$ref_code',
	'$user_id',
	'$package_name',
	'$package_price',
	'1',
	'1',
	'$created_date'
	)";		
	$result_package = $mysqli->query($query_package);

	//Get active package sum
	$data_total_sum =
	"select SUM(package_price) As num 
	from package_sale
	Where ref_code ='$ref_code'
	And status='1' ";    
	$result_total_sum = $mysqli-> query($data_total_sum);
	if ($result_total_sum -> num_rows > 0)
	{
		$row_total_sum = $result_total_sum ->fetch_assoc();
		$total_sum = $row_total_sum['num'];
	}

	//Get upline info
	$sql_sponsorlvl1 = "SELECT *
	FROM user
	Where ref_code = '$ref_code'
	And status = '1'";
	$result_sponsorlvl1 = $mysqli-> query($sql_sponsorlvl1);
	if ($result_sponsorlvl1 -> num_rows > 0)
	{
		$row_sponsorlvl1 = $result_sponsorlvl1 ->fetch_assoc();
		$My_sponsor_code = $row_sponsorlvl1['sponsor_code'];
		$My_helper_code = $row_sponsorlvl1['helper_code'];
		$buyer_ref_code = $row_sponsorlvl1['ref_code'];
		$buyer_name = $row_sponsorlvl1['nick_name'];

		//If got Helper that Helper 3% and Sponsor 7%...but if don't have helper then Sponsor 10%'
		if ($My_helper_code != "")
		{
		    //For Sponsor 7%
			$commission_percent = 0.07 ;
			$commission_percent_display = 7 ;
			$my_ref_code = $My_sponsor_code;

			Profit_Sharing_Commission($buyer_ref_code, $my_ref_code, $buyer_name, $commission_percent, $commission_percent_display, $package_name, $package_price, $trans_code);

			//For Helper 3%
			$commission_percent = 0.03 ;
			$commission_percent_display = 3 ;
			$my_ref_code = $My_helper_code;

			Profit_Sharing_Commission($buyer_ref_code, $my_ref_code, $buyer_name, $commission_percent, $commission_percent_display, $package_name, $package_price, $trans_code);
		}
		else
		{
			//For Sponsor 10%
			$commission_percent = 0.10 ;
			$commission_percent_display = 10 ;
			$my_ref_code = $My_sponsor_code;

			Profit_Sharing_Commission($buyer_ref_code, $my_ref_code, $buyer_name, $commission_percent, $commission_percent_display, $package_name, $package_price, $trans_code);
		}
	}

	if($resUpdate_my_wallet && $res_purchase && $resUpdate_hq_wallet && $res_hq_activation_charge && $result_package)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Purchase New Package');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_package.php'; </script>";
		//echo "<script type='text/javascript'> document.location='../U/checkout_proceed_B_payment_package_toyyibpay.php?purchase_code=$purchase_code'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_package.php'; </script>";
	}
}
?>

<?php
function Profit_Sharing_Commission($buyer_ref_code, $my_ref_code, $buyer_name, $commission_percent, $commission_percent_display, $package_name, $package_price, $trans_code)
{
	global $mysqli;
	
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');
	
	//Get upline wallet info
	$sql_sponsor_wallet = "SELECT * 
	FROM wallet
	WHERE ref_code='$my_ref_code' LIMIT 1";
	$result_sponsor_wallet = $mysqli-> query($sql_sponsor_wallet);
	if ($result_sponsor_wallet -> num_rows > 0)
	{
		$row_sponsor_wallet = $result_sponsor_wallet ->fetch_assoc();
		$my_cash_wallet = $row_sponsor_wallet['cash_wallet'];
	}

	$total_my_commission = $commission_percent * $package_price;
	//$total_my_commission = number_format($total_my_commission,2);
	$new_my_cash_wallet = $my_cash_wallet + $total_my_commission;
	//$new_my_cash_wallet = number_format($new_my_cash_wallet,2);

	//Update upline wallet
	$Update_sponsor_wallet = "UPDATE wallet SET
	cash_wallet='$new_my_cash_wallet'
	WHERE ref_code = '$my_ref_code' ";
	$result_sponsor_wallet = $mysqli->query($Update_sponsor_wallet);

	$status_commission = '1';
	$in_transactions_commission = $total_my_commission;
	$out_transactions_commission = 0 ;
	$description_commission = "Level 1 Profit Sharing Commission $commission_percent_display% from new purchase of package $package_name| $package_price From $buyer_ref_code | $buyer_name" ;
	
	if ($commission_percent_display == "3")
	{
	    $type_of_process_commission = "Helper Member Profit Sharings";
	}
	else
	{
	    $type_of_process_commission = "Member Profit Sharings";
	}
	
	$balance_commission = $new_my_cash_wallet;
	$type_of_transaction_commission = "CW" ;

	$query_my_transactions_commission  = "INSERT INTO transactions
	(
	user_ref_code,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	balance,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$my_ref_code',
	'$trans_code',
	'$type_of_process_commission',
	'$type_of_transaction_commission',
	'$in_transactions_commission',
	'$out_transactions_commission',
	'$balance_commission',
	'$description_commission',
	'$status_commission',
	'$created_date'
	)";
	$res_my_transactions_commission = $mysqli->query($query_my_transactions_commission);
}
?>

<?php
session_start();

if (isset($_POST['forget_password'])) 
{
    $email  = htmlspecialchars($_POST['email'], ENT_QUOTES);
	$username  = htmlspecialchars($_POST['username'], ENT_QUOTES);

	$new_password = randomRefferalCode();

    $sql = "SELECT * 
	FROM user 
	WHERE email='$email' 
	And nick_name='$username'
	And status='1'
	LIMIT 1";
	$result = $mysqli-> query($sql);
	if ($result -> num_rows > 0)
	{
		$row = $result ->fetch_assoc();
		$user_id = $row['id'];
		$phone_number = $row['phone_number'];

		$countryCode = '60';
		$firstCharacter = substr($phone_number, 0, 1);
		if ($firstCharacter == "0")
		{
			$phone_number = substr($phone_number,1);
		}

		$phone_number = $countryCode.$phone_number;
	}
	else   
	{
        echo "<script type='text/javascript'>alert('Fail.This email not registered with us.Please purchase package first');</script>";
        echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/senarai-pakej/'; </script>";
		exit();
    } 

	$mysqli->begin_transaction();

	$UpdateQuery1 = "UPDATE user SET   
	password ='$new_password' 
	WHERE id ='$user_id'";
    $resUpdateUser = $mysqli->query($UpdateQuery1);
    
    if ($resUpdateUser ) 
	{
        $mysqli->commit();
        
		/********************** SMS To User Start*************************************************/
		/*
		$message = "RM0 UMRAH HAJI MABRUR SDN BHD: Your new password is $new_password";

		$curl = curl_init();
		$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
		$params = array(
		'username' => 'mygoldplt_websystemmabrur',
		'password' => 'mygoldplt_websystemmabrur123',
		'message' => $message,
		'mobile' => $phone_number,
		'Sender' => 'Test',
		'type' => '1'
		);
		$url = $endpoint . '?' . http_build_query($params);
		curl_setopt($curl, CURLOPT_URL, $url);

		$result = curl_exec($curl);
		$info = curl_getinfo($curl);  
		curl_close($curl);
		$obj = json_decode($result);

		//echo "<script type='text/javascript'>alert('$result);</script>";
		*/
		/********************** SMS To User End*************************************************/
		
		/********************** Email To User *************************************************/
		$to = $email;
		$subject = "Hi $email, mygoldsdnbhd.com Password Reset";
        
		$message = "
		<html>
		<head>
		<title>Hi $email, mygoldsdnbhd.com Password Reset</title>
		</head>
		<body>
		<p>

		Hai $email,<br><br>

		Please login to your account using this new password:  <b>$new_password</b><br>
		</p>

		</body>
		</html>
		";
        
		// Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
		// More headers
		$headers .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
		$headers .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
		$headers .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
		mail($to, $subject, $message, $headers);
		/********************** Email To User *************************************************/

        echo "<script type='text/javascript'>alert('Thank you.Password reset info has been send to your email and SMS');</script>";
        echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/log-masuk/'; </script>";
		exit();    
    } 
	else 
	{
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail');</script>";
        echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/reset-kata-laluan/'; </script>";
		exit();
    }
}

?>

<?php
if (isset($_POST['user_update_personal_detail'])) 
{
    
    $id = $_POST['id'];
	$ref_code = $_POST['ref_code'];
    
    $name1 = $_POST['name'];
    $name  = htmlspecialchars($name1, ENT_QUOTES);

	$nick_name1 = $_POST['nick_name'];
    $nick_name  = htmlspecialchars($nick_name1, ENT_QUOTES);
    
    $phone_number = $_POST['phone_number'];
        
    $password1 = $_POST['password'];
    $password  = htmlspecialchars($password1, ENT_QUOTES);

	$bank_type = $_POST['bank_type'];
	$acc_no = $_POST['acc_no'];
	
	$acc_holder1 = $_POST['acc_holder'];
    $acc_holder  = htmlspecialchars($acc_holder1, ENT_QUOTES);
	
	$address1 = $_POST['address'];
    $address  = htmlspecialchars($address1, ENT_QUOTES);

	$state1 = $_POST['state'];
    $state  = htmlspecialchars($state1, ENT_QUOTES);
	   
    date_default_timezone_set("Asia/Kuala_Lumpur");
    $updated_date = date('Y-m-d H:i:s');
    
	$mysqli->begin_transaction();
    
    if ($_FILES['profile_image']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["profile_image"]["name"]);
		$newfilename1 = $ref_code . $time_stamp. '.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{

			$check1 = getimagesize($_FILES["profile_image"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

			

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["profile_image"]["tmp_name"], $target_file1)  )
			{
				$profile_image = $ref_code . $time_stamp. '.' . end($temp1);

				//Insert downline package detail into package_sale table
				$UpdateQuery = "UPDATE user SET  
				name='$name',
				nick_name='$nick_name',
				phone_number='$phone_number',
				password='$password',
				bank_type='$bank_type',
				acc_no='$acc_no',
				acc_holder='$acc_holder',
				address='$address',
				state='$state',
				profile_image='$profile_image'
				WHERE id='$id' ";
				$result = $mysqli->query($UpdateQuery);

			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/profile.php?ref_code=$ref_code'; </script>";
				exit();
			}
		}
	}
	else 
	{
		$UpdateQuery = "UPDATE user SET  
		name='$name',
		nick_name='$nick_name',
		phone_number='$phone_number',
		password='$password',
		bank_type='$bank_type',
		acc_no='$acc_no',
		acc_holder='$acc_holder',
		address='$address',
		state='$state'
		WHERE id='$id' ";
		$result = $mysqli->query($UpdateQuery1);
    }

    if ($result) 
	{	    
		$mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully updated profile');</script>";
        echo "<script type='text/javascript'> document.location='../U/profile.php?ref_code=$ref_code'; </script>";
		exit();
    }
    
    else 
	{   
	    $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail. Please try again');</script>";
        echo "<script type='text/javascript'> document.location='../U/profile.php?ref_code=$ref_code'; </script>";
		exit();
    } 
}
?>


<?php
if (isset($_POST['Add_Referral_Bonus_Setting'])) 
{	
	$level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$commission_percent = htmlspecialchars($_POST['commission_percent'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_referral  = "INSERT INTO referral_bonus
	(
	level_number, 
	commission_percent,		
	status, 
	created_date
	)
	VALUES
	(
	'$level_number', 
	'$commission_percent',
	'$status', 
	'$created_date'
	)";		
	$result_referral = $mysqli->query($query_referral);

	if($result_referral)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Bonus Referral Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Referral_Bonus_Setting'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$commission_percent = htmlspecialchars($_POST['commission_percent'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE referral_bonus SET  
	level_number='$level_number', 
	commission_percent='$commission_percent'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Referral_Bonus_Setting'])) 
{
	$id = $_POST['id'];
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE referral_bonus SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully delete referral bonus setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/referral_bonus_setting_1.php'; </script>";
	}        
}
?>

<?php
if (isset($_POST['Add_Profit_Sharing_Setting'])) 
{	
	$level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$commission_percent = htmlspecialchars($_POST['commission_percent'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_referral  = "INSERT INTO profit_sharing
	(
	level_number, 
	commission_percent,		
	status, 
	created_date
	)
	VALUES
	(
	'$level_number', 
	'$commission_percent',
	'$status', 
	'$created_date'
	)";		
	$result_referral = $mysqli->query($query_referral);

	if($result_referral)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Bonus Referral Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Profit_Sharing_Setting'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$commission_percent = htmlspecialchars($_POST['commission_percent'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE profit_sharing SET  
	level_number='$level_number', 
	commission_percent='$commission_percent'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Profit_Sharing_Setting'])) 
{
	$id = $_POST['id'];
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE profit_sharing SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully delete profit sharing setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_1.php'; </script>";
	}        
}
?>

<?php
if (isset($_POST['Add_Profit_Sharing_Schedule_Setting'])) 
{	
	$Roi = htmlspecialchars($_POST['Roi'], ENT_QUOTES);
	$Process_Date = htmlspecialchars($_POST['Process_Date'], ENT_QUOTES);

	$sql = "SELECT * 
	FROM profit_sharing_scheduler 
	WHERE Process_Date ='$Process_Date' 
	And status ='1'";
	$result = $mysqli-> query($sql);
	if ($result -> num_rows > 0)
	{
		$row = $result ->fetch_assoc();
		echo "<script type='text/javascript'>alert('Fail. Profit Sharing Schedule Settings for $Process_Date already being setup.');</script>";
        echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d');

   	$mysqli->begin_transaction();

	$query_referral  = "INSERT INTO profit_sharing_scheduler
	(
	Roi, 
	Process_Date,		
	status, 
	created_date
	)
	VALUES
	(
	'$Roi', 
	'$Process_Date',
	'$status', 
	'$created_date'
	)";		
	$result_referral = $mysqli->query($query_referral);

	if($result_referral)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Profit Sharing Schedule Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['Update_Profit_Sharing_Schedule_Setting'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$Roi = htmlspecialchars($_POST['Roi'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE profit_sharing_scheduler SET  
	Roi='$Roi'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Profit Sharing Schedule Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";	 
		exit();
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}     
}
?>

<?php
if (isset($_POST['Delete_Profit_Sharing_Schedule_Setting'])) 
{
	$id = $_POST['id'];
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE profit_sharing_scheduler SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Profit Sharing Schedule Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/profit_sharing_setting_schedule_1.php'; </script>";
		exit();
	}        
}
?>


<?php
if (isset($_POST['Wallet_Topup'])) 
{	
	$ref_code = strtoupper(htmlspecialchars($_POST['ref_code'], ENT_QUOTES));
	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');

	$mysqli->begin_transaction();

	//Check existing user topup
    $sql_check_ext_topup = "SELECT * 
	FROM topup_wallet 
	WHERE ref_code = '$ref_code'
	AND topup_status IN ('1','2') ";
	$result_check_ext_topup = $mysqli-> query($sql_check_ext_topup);
	if ($result_check_ext_topup -> num_rows < 1)
	{
		$row_check_ext_topup = $result_check_ext_topup ->fetch_assoc();

		//Looping through each user 
		$query_user = "SELECT *
		FROM user
		WHERE ref_code != 'MGP10000'
		AND ref_code = '$ref_code'
		AND status = '1'";
		$result_user = $mysqli-> query($query_user);
		if ($result_user -> num_rows > 0)
		{
			while($record_user = $result_user -> fetch_assoc())
			{    
				$user_id= $record_user['id'];
				$ref_code= $record_user['ref_code'];

				$query_transaction = "SELECT *
				FROM transactions
				Where user_ref_code = '$ref_code'
				AND type_of_process = 'Member Profit Sharings'
				AND created_date > '2022-08-17 00:00'
				AND created_date < '2022-08-17 07:00'
				AND status = '1'";
				$result_transaction = $mysqli-> query($query_transaction);
				if ($result_transaction -> num_rows > 0)
				{
					while($record_transaction = $result_transaction -> fetch_assoc())
					{    
						$transaction_id = $record_transaction['id'];
						$balance = number_format($record_transaction['balance'],2); 

						$sql_next_transaction = "SELECT *
						FROM transactions
						Where user_ref_code = '$ref_code'
						AND type_of_process = 'Member Profit Sharings'
						AND created_date > '2022-08-17 00:00'
						AND created_date < '2022-08-17 07:00'
						AND status = '1'
						AND id > $transaction_id
						LIMIT 1";
						$result_next_transaction = $mysqli-> query($sql_next_transaction);
						if ($result_next_transaction -> num_rows > 0)
						{
							$row_next_transaction = $result_next_transaction ->fetch_assoc();
							$next_balance = number_format($row_next_transaction['balance'],2);  

							if ($next_balance < $balance && $next_balance >  '0')
							{
								$topup_balance = $balance - $next_balance;
					
								$query_topup_wallet  = "INSERT INTO topup_wallet
								(
								ref_code,
								balance,
								next_balance,
								topup,
								status,
								topup_status,
								created_date
								)
								VALUES
								(
								'$ref_code',
								'$balance',
								'$next_balance',
								'$topup_balance',
								'1',
								'1',
								'$created_date'
								)";
								$res_topup_wallet = $mysqli->query($query_topup_wallet);

								$sql_my_wallet = "SELECT * 
								FROM wallet
								WHERE ref_code='$ref_code' LIMIT 1";
								$result_my_wallet = $mysqli-> query($sql_my_wallet);
								if ($result_my_wallet -> num_rows > 0)
								{
									$row_my_wallet = $result_my_wallet ->fetch_assoc();
									$my_cash_wallet = $row_my_wallet['cash_wallet'];
								}

								$new_my_cash_wallet = $my_cash_wallet + $topup_balance;

								$Update_my_wallet = "UPDATE wallet SET
								cash_wallet='$new_my_cash_wallet'
								WHERE ref_code = '$ref_code' ";
								$result_my_wallet = $mysqli->query($Update_my_wallet);
							}
						}	
					}
				}	
			}
		}
	}

	//Check existing user topup_investment
    $sql_check_ext_topup = "SELECT * 
	FROM topup_wallet 
	WHERE ref_code = '$ref_code'
	AND topup_investment_status IN ('1','2') ";
	$result_check_ext_topup = $mysqli-> query($sql_check_ext_topup);
	if ($result_check_ext_topup -> num_rows < 1)
	{
		$row_check_ext_topup = $result_check_ext_topup ->fetch_assoc();

		//Looping through each user 
		$query_user = "SELECT *
		FROM user
		WHERE ref_code != 'MGP10000'
		AND ref_code = '$ref_code'
		AND status = '1'";
		$result_user = $mysqli-> query($query_user);
		if ($result_user -> num_rows > 0)
		{
			while($record_user = $result_user -> fetch_assoc())
			{ 
				$user_id= $record_user['id'];
				$ref_code= $record_user['ref_code'];

				$query_transaction = "SELECT *
				FROM transactions
				Where user_ref_code = '$ref_code'
				AND type_of_process = 'Member Investment Profit'
				AND created_date > '2022-08-16 00:00'
				AND created_date < '2022-08-19 23:00'
				AND status = '1'";
				$result_transaction = $mysqli-> query($query_transaction);
				if ($result_transaction -> num_rows > 0)
				{
					while($record_transaction = $result_transaction -> fetch_assoc())
					{ 
						$transaction_id = $record_transaction['id'];
						$balance = number_format($record_transaction['balance'],2); 
						$created_date = $record_transaction['created_date'];

						$variable = $created_date;
						$variable = substr($variable, 0, strpos($variable, " "));

						$sql_next_transaction = "SELECT *
						FROM transactions
						Where user_ref_code = '$ref_code'
						AND type_of_process = 'Member Investment Profit'
						AND created_date > '2022-08-16 00:00'
						AND created_date < '2022-08-19 23:00'
						AND status = '1'
						AND id > $transaction_id
						LIMIT 1";
						$result_next_transaction = $mysqli-> query($sql_next_transaction);
						if ($result_next_transaction -> num_rows > 0)
						{
							$row_next_transaction = $result_next_transaction ->fetch_assoc();
							$next_balance = number_format($row_next_transaction['balance'],2);  

							if ($next_balance < $balance && $next_balance >  '0')
							{
								$topup_balance = $balance - $next_balance;

								$data_total_withdraw =
								"Select SUM(amount) As num 
								from withdraw_transaction
								Where ref_code = '$ref_code'
								And tac_verify_status = '1' 
								And created_date = '$variable'";  
								$result_total_withdraw = $mysqli-> query($data_total_withdraw);
								if ($result_total_withdraw -> num_rows > 0)
								{
									$row_total_withdraw = $result_total_withdraw ->fetch_assoc();
									$full_total_withdraw = $row_total_withdraw['num'];
								}

								$topup_balance = $topup_balance - $full_total_withdraw;
					
								$query_topup_wallet  = "INSERT INTO topup_wallet
								(
								ref_code,
								balance,
								next_balance,
								topup,
								withdraw,
								status,
								topup_investment_status,
								created_date
								)
								VALUES
								(
								'$ref_code',
								'$balance',
								'$next_balance',
								'$topup_balance',
								'$full_total_withdraw',
								'1',
								'1',
								'$created_date'
								)";
								$res_topup_wallet = $mysqli->query($query_topup_wallet);

								$sql_my_wallet = "SELECT * 
								FROM wallet
								WHERE ref_code='$ref_code' LIMIT 1";
								$result_my_wallet = $mysqli-> query($sql_my_wallet);
								if ($result_my_wallet -> num_rows > 0)
								{
									$row_my_wallet = $result_my_wallet ->fetch_assoc();
									$my_cash_wallet = $row_my_wallet['cash_wallet'];
								}

								$new_my_cash_wallet = $my_cash_wallet + $topup_balance;

								$Update_my_wallet = "UPDATE wallet SET
								cash_wallet='$new_my_cash_wallet'
								WHERE ref_code = '$ref_code' ";
								$result_my_wallet = $mysqli->query($Update_my_wallet);
							}
						}
					}
				}	
			}
		}
	}

	$Update_balance_status = "UPDATE user SET
	balance_status='1'
	WHERE ref_code = '$ref_code' ";
	$result_balance_status = $mysqli->query($Update_balance_status);

	if($result_balance_status)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Process This Member');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_topup_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_topup_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Add_Rank_Setting'])) 
{	
	$level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$level_name = htmlspecialchars($_POST['level_name'], ENT_QUOTES);
	$minimum_package_purchase = htmlspecialchars($_POST['minimum_package_purchase'], ENT_QUOTES);
	$maximum_package_purchase = htmlspecialchars($_POST['maximum_package_purchase'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_level  = " INSERT INTO user_level
	(
	level_number, 
	level_name,	
	minimum_package_purchase,	
	maximum_package_purchase,
	status, 
	created_date
	)
	VALUES
	(
	'$level_number', 
	'$level_name',
	'$minimum_package_purchase',	
	'$maximum_package_purchase',
	'$status', 
	'$created_date'
	)";		
	$result_level = $mysqli->query($query_level);

	if($result_level)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Rank Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Rank_Setting'])) 
{
	$id = $_POST['id'];
    $level_number = htmlspecialchars($_POST['level_number'], ENT_QUOTES);
	$level_name = htmlspecialchars($_POST['level_name'], ENT_QUOTES);
	$minimum_package_purchase = htmlspecialchars($_POST['minimum_package_purchase'], ENT_QUOTES);
	$maximum_package_purchase = htmlspecialchars($_POST['maximum_package_purchase'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE user_level SET  
	level_number='$level_number', 
	level_name='$level_name',
	minimum_package_purchase='$minimum_package_purchase',
	maximum_package_purchase='$maximum_package_purchase'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Rank_Setting'])) 
{
	$id = $_POST['id'];
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE user_level SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully delete rank setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/rank_setting_1.php'; </script>";
	}        
}
?>

<?php
if (isset($_POST['Add_Package_Setting'])) 
{	
    $package_ref_code = randomRefferalCode();
	$package_name = htmlspecialchars($_POST['package_name'], ENT_QUOTES);
	$package_price = htmlspecialchars($_POST['package_price'], ENT_QUOTES);

    $bonus_sponsor = htmlspecialchars($_POST['bonus_sponsor'], ENT_QUOTES);
    $hibah_unilevel_1 = htmlspecialchars($_POST['hibah_unilevel_1'], ENT_QUOTES);
    $hibah_unilevel_2 = htmlspecialchars($_POST['hibah_unilevel_2'], ENT_QUOTES);
    $hibah_unilevel_3 = htmlspecialchars($_POST['hibah_unilevel_3'], ENT_QUOTES);

	$status = 1;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_package  = "INSERT INTO package_setting
	(
	    package_ref_code,
	    package_name,
	    package_price,
        bonus_sponsor,
        hibah_unilevel_1,
        hibah_unilevel_2,
        hibah_unilevel_3,
	    status,
	    created_date
	)
	VALUES
	(
	    '$package_ref_code',
	    '$package_name',
	    '$package_price',
        '$bonus_sponsor',
        '$hibah_unilevel_1',
        '$hibah_unilevel_2',
        '$hibah_unilevel_3',
	    '$status',
	    '$created_date'
	)";		

	$result_package = $mysqli->query($query_package);

	if($result_package)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Package Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Package_Setting'])) 
{
	$id = $_POST['id'];
	$package_name = htmlspecialchars($_POST['package_name'], ENT_QUOTES);
	$package_price = htmlspecialchars($_POST['package_price'], ENT_QUOTES);

    $bonus_sponsor = htmlspecialchars($_POST['bonus_sponsor'], ENT_QUOTES);
    $hibah_unilevel_1 = htmlspecialchars($_POST['hibah_unilevel_1'], ENT_QUOTES);
    $hibah_unilevel_2 = htmlspecialchars($_POST['hibah_unilevel_2'], ENT_QUOTES);
    $hibah_unilevel_3 = htmlspecialchars($_POST['hibah_unilevel_3'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE package_setting SET  
	    package_name='$package_name',
	    package_price='$package_price',
        bonus_sponsor='$bonus_sponsor',
        hibah_unilevel_1='$hibah_unilevel_1',
        hibah_unilevel_2='$hibah_unilevel_2',
        hibah_unilevel_3='$hibah_unilevel_3'
	WHERE id='$id' ";               

	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Package Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Package_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE package_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Package Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/package_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Add_Emas_Setting'])) 
{	
    $emas_ref_code = randomRefferalCode();
	$emas_name = htmlspecialchars($_POST['emas_name'], ENT_QUOTES);
	$emas_price = htmlspecialchars($_POST['emas_price'], ENT_QUOTES);
    $emas_sale_profit_pergram = htmlspecialchars($_POST['emas_sale_profit_pergram'], ENT_QUOTES);
    $emas_upah_simpan = htmlspecialchars($_POST['emas_upah_simpan'], ENT_QUOTES);
    $emas_buy_back_percent = htmlspecialchars($_POST['emas_buy_back_percent'], ENT_QUOTES);
    $emas_remark = htmlspecialchars($_POST['emas_remark'], ENT_QUOTES);

	$status = 1;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_emas = "INSERT INTO emas_setting
	(
	    emas_ref_code,
	    emas_name,
	    emas_price,
        emas_sale_profit_pergram,
        emas_upah_simpan,
        emas_buy_back_percent,
        emas_remark,
	    status,
	    created_date
	)
	VALUES
	(
	    '$emas_ref_code',
	    '$emas_name',
	    '$emas_price',
        '$emas_sale_profit_pergram',
        '$emas_upah_simpan',
        '$emas_buy_back_percent',
        '$emas_remark',
	    '$status',
	    '$created_date'
	)";		

	$result_emas = $mysqli->query($query_emas);

	if($result_emas)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Emas Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Emas_Setting'])) 
{
	$id = $_POST['id'];
	$emas_name = htmlspecialchars($_POST['emas_name'], ENT_QUOTES);
	$emas_price = htmlspecialchars($_POST['emas_price'], ENT_QUOTES);
    $emas_sale_profit_pergram = htmlspecialchars($_POST['emas_sale_profit_pergram'], ENT_QUOTES);
    $emas_upah_simpan = htmlspecialchars($_POST['emas_upah_simpan'], ENT_QUOTES);
    $emas_buy_back_percent = htmlspecialchars($_POST['emas_buy_back_percent'], ENT_QUOTES);
    $emas_remark = htmlspecialchars($_POST['emas_remark'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE emas_setting SET  
	    emas_name='$emas_name',
	    emas_price='$emas_price',
        emas_sale_profit_pergram='$emas_sale_profit_pergram',
        emas_upah_simpan='$emas_upah_simpan',
        emas_buy_back_percent='$emas_buy_back_percent',
        emas_remark='$emas_remark'
	WHERE id='$id' ";               

	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Emas Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Emas_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE emas_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Emas Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/emas_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Add_Sales_Bonus_Setting'])) 
{	
    $sales_bonus_ref_code = randomRefferalCode();
	$emas_setting_id = htmlspecialchars($_POST['emas_setting_id'], ENT_QUOTES);
	$name_of_bonus = htmlspecialchars($_POST['name_of_bonus'], ENT_QUOTES);
    $total_gold_weight = htmlspecialchars($_POST['total_gold_weight'], ENT_QUOTES);
    $bonus_amount = htmlspecialchars($_POST['bonus_amount'], ENT_QUOTES);
    $addon_incentive_percent = htmlspecialchars($_POST['addon_incentive_percent'], ENT_QUOTES);
    $bonus_remark = htmlspecialchars($_POST['bonus_remark'], ENT_QUOTES);

	$status = 1;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_sales_bonus = "INSERT INTO `Sales_Bonus_Setting`
	(
	    sales_bonus_ref_code,
	    emas_setting_id,
	    name_of_bonus,
        total_gold_weight,
        bonus_amount,
        addon_incentive_percent,
        bonus_remark,
	    status,
	    created_date
	)
	VALUES
	(
	    '$sales_bonus_ref_code',
	    '$emas_setting_id',
	    '$name_of_bonus',
        '$total_gold_weight',
        '$bonus_amount',
        '$addon_incentive_percent',
        '$bonus_remark',
	    '$status',
	    '$created_date'
	)";		

	$result_sales_bonus = $mysqli->query($query_sales_bonus);

	if($result_sales_bonus)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Sales Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Sales_Bonus_Setting'])) 
{
	$id = $_POST['id'];
	$emas_setting_id = htmlspecialchars($_POST['emas_setting_id'], ENT_QUOTES);
	$name_of_bonus = htmlspecialchars($_POST['name_of_bonus'], ENT_QUOTES);
    $total_gold_weight = htmlspecialchars($_POST['total_gold_weight'], ENT_QUOTES);
    $bonus_amount = htmlspecialchars($_POST['bonus_amount'], ENT_QUOTES);
    $addon_incentive_percent = htmlspecialchars($_POST['addon_incentive_percent'], ENT_QUOTES);
    $bonus_remark = htmlspecialchars($_POST['bonus_remark'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Sales_Bonus_Setting` SET  
	    emas_setting_id='$emas_setting_id',
	    name_of_bonus='$name_of_bonus',
        total_gold_weight='$total_gold_weight',
        bonus_amount='$bonus_amount',
        addon_incentive_percent='$addon_incentive_percent',
        bonus_remark='$bonus_remark'
	WHERE id='$id' ";               

	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Sales Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Sales_Bonus_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Sales_Bonus_Setting` SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Sales Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/sales_bonus_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Add_Manager_Level_Bonus_Setting'])) 
{	
    $manager_level_bonus_ref_code = randomRefferalCode();
	$emas_setting_id = htmlspecialchars($_POST['emas_setting_id'], ENT_QUOTES);
	$name_of_bonus = htmlspecialchars($_POST['name_of_bonus'], ENT_QUOTES);
    $total_sales = htmlspecialchars($_POST['total_sales'], ENT_QUOTES);
    $bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);
    $bonus_remark = htmlspecialchars($_POST['bonus_remark'], ENT_QUOTES);

	$status = 1;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_manager_level_bonus = "INSERT INTO `Manager_Level_Bonus_Setting`
	(
	    manager_level_bonus_ref_code,
	    emas_setting_id,
	    name_of_bonus,
        total_sales,
        bonus_percent,
        bonus_remark,
	    status,
	    created_date
	)
	VALUES
	(
	    '$manager_level_bonus_ref_code',
	    '$emas_setting_id',
	    '$name_of_bonus',
        '$total_sales',
        '$bonus_percent',
        '$bonus_remark',
	    '$status',
	    '$created_date'
	)";		

	$result_manager_level_bonus = $mysqli->query($query_manager_level_bonus);

	if($result_manager_level_bonus)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Manager Level Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Manager_Level_Bonus_Setting'])) 
{
	$id = $_POST['id'];
	$emas_setting_id = htmlspecialchars($_POST['emas_setting_id'], ENT_QUOTES);
	$name_of_bonus = htmlspecialchars($_POST['name_of_bonus'], ENT_QUOTES);
    $total_sales = htmlspecialchars($_POST['total_sales'], ENT_QUOTES);
    $bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);
    $bonus_remark = htmlspecialchars($_POST['bonus_remark'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Manager_Level_Bonus_Setting` SET  
	    emas_setting_id='$emas_setting_id',
	    name_of_bonus='$name_of_bonus',
        total_sales='$total_sales',
        bonus_percent='$bonus_percent',
        bonus_remark='$bonus_remark'
	WHERE id='$id' ";               

	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Manager Level Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Manager_Level_Bonus_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Manager_Level_Bonus_Setting` SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Manager Level Bonus Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_bonus_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Add_Manager_Level_Setting'])) 
{	
    $manager_level_ref_code = randomRefferalCode();
	$name_of_level = htmlspecialchars($_POST['name_of_level'], ENT_QUOTES);
    $bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);
    $level_remark = htmlspecialchars($_POST['level_remark'], ENT_QUOTES);

	$status = 1;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_manager_level = "INSERT INTO `Manager_Level_Setting`
	(
	    manager_level_ref_code,
	    name_of_level,
        bonus_percent,
        level_remark,
	    status,
	    created_date
	)
	VALUES
	(
	    '$manager_level_ref_code',
	    '$name_of_level',
        '$bonus_percent',
        '$level_remark',
	    '$status',
	    '$created_date'
	)";		

	$result_manager_level = $mysqli->query($query_manager_level);

	if($result_manager_level)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Manager Level Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Manager_Level_Setting'])) 
{
	$id = $_POST['id'];
	$name_of_level = htmlspecialchars($_POST['name_of_level'], ENT_QUOTES);
    $bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);
    $level_remark = htmlspecialchars($_POST['level_remark'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Manager_Level_Setting` SET  
	    name_of_level='$name_of_level',
        bonus_percent='$bonus_percent',
        level_remark='$level_remark'
	WHERE id='$id' ";               

	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Manager Level Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Manager_Level_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery = "UPDATE `Manager_Level_Setting` SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Manager Level Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/manager_level_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Update_Hibah_Unilevel_Setting']))
{
    $id = $_POST['id'];
    $level_1 = htmlspecialchars($_POST['level_1'], ENT_QUOTES);
    $level_2 = htmlspecialchars($_POST['level_2'], ENT_QUOTES);
    $level_3 = htmlspecialchars($_POST['level_3'], ENT_QUOTES);

    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE hibah_unilevel_setting SET
                    level_1 = '$level_1',
                    level_2 = '$level_2',
                    level_3 = '$level_3'
                    WHERE id = '$id'";
    $result = $mysqli->query($UpdateQuery);

    if ($result)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Update Hibah Unilevel Setting');</script>";
        echo "<script type='text/javascript'> document.location='../U/hibah_unilevel_setting.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/hibah_unilevel_setting.php'; </script>";
    }
}
?>

<?php
if (isset($_POST['Update_Commission_Setting'])) 
{
	$package_ref_code = $_POST['package_ref_code'];
	$level_1 = htmlspecialchars($_POST['level_1'], ENT_QUOTES);
	$level_1_1 = htmlspecialchars($_POST['level_1_1'], ENT_QUOTES);
	$level_2 = htmlspecialchars($_POST['level_2'], ENT_QUOTES);
	$level_3 = htmlspecialchars($_POST['level_3'], ENT_QUOTES);
	$level_4 = htmlspecialchars($_POST['level_4'], ENT_QUOTES);
	$level_5 = htmlspecialchars($_POST['level_5'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE commission_setting SET  
	level_1='$level_1', 
	level_1_1='$level_1_1', 
	level_2='$level_2', 
	level_3='$level_3', 
	level_4='$level_4', 
	level_5='$level_5'
	WHERE package_ref_code='$package_ref_code' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Commission Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/commission_setting_1.php?package_ref_code=$package_ref_code'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/commission_setting_1.php?package_ref_code=$package_ref_code'; </script>";	 
	}     
}
?>

<?php
if (isset($_POST['Delete_Commission_Setting'])) 
{
	$id = $_POST['id'];
	$package_ref_code = $_POST['package_ref_code'];

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE commission_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Package Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/commission_setting_1.php?package_ref_code=$package_ref_code'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/commission_setting_1.php?package_ref_code=$package_ref_code'; </script>";	   
	}     
}
?>

<?php
if (isset($_POST['Add_Inventory_Setting'])) 
{	
    $item_ref_code = randomRefferalCode();
	$item_name = htmlspecialchars($_POST['item_name'], ENT_QUOTES);
	$item_year = htmlspecialchars($_POST['item_year'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_inventory  = " INSERT INTO item_inventory
	(
	item_ref_code, 
	item_year,	
	item_name,	
	status, 
	created_date
	)
	VALUES
	(
	'$item_ref_code', 
	'$item_year',	
	'$item_name',	
	'$status', 
	'$created_date'
	)";		
	$result_inventory = $mysqli->query($query_inventory);

	if($result_inventory)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Item');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Inventory_Setting'])) 
{
	$id = $_POST['id'];
	$item_name = htmlspecialchars($_POST['item_name'], ENT_QUOTES);
	$in_1 = htmlspecialchars($_POST['in_1'], ENT_QUOTES);
	$out_1 = htmlspecialchars($_POST['out_1'], ENT_QUOTES);
	$balance_1 = htmlspecialchars($_POST['balance_1'], ENT_QUOTES);
	$in_2 = htmlspecialchars($_POST['in_2'], ENT_QUOTES);
	$out_2 = htmlspecialchars($_POST['out_2'], ENT_QUOTES);
	$balance_2 = htmlspecialchars($_POST['balance_2'], ENT_QUOTES);
	$in_3 = htmlspecialchars($_POST['in_3'], ENT_QUOTES);
	$out_3 = htmlspecialchars($_POST['out_3'], ENT_QUOTES);
	$balance_3 = htmlspecialchars($_POST['balance_3'], ENT_QUOTES);
	$in_4 = htmlspecialchars($_POST['in_4'], ENT_QUOTES);
	$out_4 = htmlspecialchars($_POST['out_4'], ENT_QUOTES);
	$balance_4 = htmlspecialchars($_POST['balance_4'], ENT_QUOTES);
	$in_5 = htmlspecialchars($_POST['in_5'], ENT_QUOTES);
	$out_5 = htmlspecialchars($_POST['out_5'], ENT_QUOTES);
	$balance_5 = htmlspecialchars($_POST['balance_5'], ENT_QUOTES);
	$in_6 = htmlspecialchars($_POST['in_6'], ENT_QUOTES);
	$out_6 = htmlspecialchars($_POST['out_6'], ENT_QUOTES);
	$balance_6 = htmlspecialchars($_POST['balance_6'], ENT_QUOTES);
	$in_7 = htmlspecialchars($_POST['in_7'], ENT_QUOTES);
	$out_7 = htmlspecialchars($_POST['out_7'], ENT_QUOTES);
	$balance_7 = htmlspecialchars($_POST['balance_7'], ENT_QUOTES);
	$in_8 = htmlspecialchars($_POST['in_8'], ENT_QUOTES);
	$out_8 = htmlspecialchars($_POST['out_8'], ENT_QUOTES);
	$balance_8 = htmlspecialchars($_POST['balance_8'], ENT_QUOTES);
	$in_9 = htmlspecialchars($_POST['in_9'], ENT_QUOTES);
	$out_9 = htmlspecialchars($_POST['out_9'], ENT_QUOTES);
	$balance_9 = htmlspecialchars($_POST['balance_9'], ENT_QUOTES);
	$in_10 = htmlspecialchars($_POST['in_10'], ENT_QUOTES);
	$out_10 = htmlspecialchars($_POST['out_10'], ENT_QUOTES);
	$balance_10 = htmlspecialchars($_POST['balance_10'], ENT_QUOTES);
	$in_11 = htmlspecialchars($_POST['in_11'], ENT_QUOTES);
	$out_11 = htmlspecialchars($_POST['out_11'], ENT_QUOTES);
	$balance_11 = htmlspecialchars($_POST['balance_11'], ENT_QUOTES);
	$in_12 = htmlspecialchars($_POST['in_12'], ENT_QUOTES);
	$out_12 = htmlspecialchars($_POST['out_12'], ENT_QUOTES);
	$balance_12 = htmlspecialchars($_POST['balance_12'], ENT_QUOTES);
	

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE item_inventory SET  
	item_name='$item_name',
	in_1='$in_1',
	out_1='$out_1',
	balance_1='$balance_1',
	in_2='$in_2',
	out_2='$out_2',
	balance_2='$balance_2',
	in_3='$in_3',
	out_3='$out_3',
	balance_3='$balance_3',
	in_4='$in_4',
	out_4='$out_4',
	balance_4='$balance_4',
	in_5='$in_5',
	out_5='$out_5',
	balance_5='$balance_5',
	in_6='$in_6',
	out_6='$out_6',
	balance_6='$balance_6',
	in_7='$in_7',
	out_7='$out_7',
	balance_7='$balance_7',
	in_8='$in_8',
	out_8='$out_8',
	balance_8='$balance_8',
	in_9='$in_9',
	out_9='$out_9',
	balance_9='$balance_9',
	in_10='$in_10',
	out_10='$out_10',
	balance_10='$balance_10',
	in_11='$in_11',
	out_11='$out_11',
	balance_11='$balance_11',
	in_12='$in_12',
	out_12='$out_12',
	balance_12='$balance_12'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Item');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Delete_Inventory_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE item_inventory SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Item');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_inventory_setting_1.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Add_Bonus_Sponsor_Setting'])) 
{	
	$package_ref_code = htmlspecialchars($_POST['package_ref_code'], ENT_QUOTES);
	$user_level = htmlspecialchars($_POST['user_level'], ENT_QUOTES);
	$bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_bonus  = "INSERT INTO bonus_sponsor_setting
	(
	package_ref_code, 
	user_level,	
	bonus_percent,		
	status, 
	created_date
	)
	VALUES
	(
	'$package_ref_code', 
	'$user_level',	
	'$bonus_percent',	
	'$status', 
	'$created_date'
	)";		
	$result_bonus = $mysqli->query($query_bonus);

	if($result_bonus)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Bonus Sponsor Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Bonus_Sponsor_Setting'])) 
{
	$id = $_POST['id'];
	$package_ref_code = htmlspecialchars($_POST['package_ref_code'], ENT_QUOTES);
	$user_level = htmlspecialchars($_POST['user_level'], ENT_QUOTES);
	$bonus_percent = htmlspecialchars($_POST['bonus_percent'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE bonus_sponsor_setting SET  
	user_level='$user_level', 
	bonus_percent='$bonus_percent'
	WHERE id='$id' ";               
	$result  = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Bonus Sponsor Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";  
	}     
}
?>

<?php
if (isset($_POST['Delete_Bonus_Sponsor_Setting'])) 
{
	$id = $_POST['id'];
	$package_ref_code = htmlspecialchars($_POST['package_ref_code'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE bonus_sponsor_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Bonus Sponsor Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/bonus_sponsor_setting_1.php?package_ref_code=$package_ref_code'; </script>";
	}     
}
?>

<?php
if (isset($_POST['Add_Unilevel_Setting'])) 
{	
	$number_of_downline = htmlspecialchars($_POST['number_of_downline'], ENT_QUOTES);
	$level_overriding = htmlspecialchars($_POST['level_overriding'], ENT_QUOTES);

	$status = 1 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_bonus  = "INSERT INTO unilevel_setting
	(
	number_of_downline, 
	level_overriding,		
	status, 
	created_date
	)
	VALUES
	(
	'$number_of_downline', 
	'$level_overriding',	
	'$status', 
	'$created_date'
	)";		
	$result_bonus = $mysqli->query($query_bonus);

	if($result_bonus)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Unilevel Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Unilevel_Setting'])) 
{
	$id = $_POST['id'];
	$number_of_downline = htmlspecialchars($_POST['number_of_downline'], ENT_QUOTES);
	$level_overriding = htmlspecialchars($_POST['level_overriding'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE unilevel_setting SET  
	number_of_downline='$number_of_downline', 
	level_overriding='$level_overriding'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Unilevel Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}     
}
?>

<?php
if (isset($_POST['Delete_Unilevel_Setting'])) 
{
	$id = $_POST['id'];

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE unilevel_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete Unilevel Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/unilevel_setting_1.php'; </script>";
	}     
}
?>

<?php
if (isset($_POST['Update_Currency_Rate_Setting'])) 
{
	$id = $_POST['id'];
	$rate_usd = htmlspecialchars($_POST['rate_usd'], ENT_QUOTES);
	$deposit_rm = htmlspecialchars($_POST['deposit_rm'], ENT_QUOTES);
	$withdrawal_rm = htmlspecialchars($_POST['withdrawal_rm'], ENT_QUOTES);
	$withdraw_fees_usd = htmlspecialchars($_POST['withdraw_fees_usd'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE currency_rate_setting SET  
	rate_usd='$rate_usd',
	deposit_rm='$deposit_rm',
	withdrawal_rm='$withdrawal_rm',
	withdraw_fees_usd='$withdraw_fees_usd'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/currency_rate_setting_1.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/currency_rate_setting_1.php'; </script>";
	}     
}
?>

<?php
if (isset($_POST['Update_Registation_Price_Setting'])) 
{
	$id = $_POST['id'];
	$price = htmlspecialchars($_POST['price'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE registration_price_setting SET  
	price='$price'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/registration_price_setting_1.php'; </script>";
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/registration_price_setting_1.php'; </script>";
	}     
}
?>


<?php
if (isset($_POST['agent_registration'])) 
{
    $sponsor_code = htmlspecialchars($_POST['sponsor_code'],ENT_QUOTES);
	$sponsor_rank = htmlspecialchars($_POST['sponsor_rank'],ENT_QUOTES);
	if ( $sponsor_code == '')
	{
	     $sponsor_code = "MG10002";  
	}
	
	$from_web = $_POST['from_web'];
	if ( $from_web == 'System')			
	{
		$page_success = "../U/add_new_user.php";
		$page_fail = "../U/add_new_user.php";
	}
	else
	{
		$page_success = "https://mygoldsdnbhd.com/registration/";
		$page_fail = "https://mygoldsdnbhd.com/registration/";
	}

	$name = htmlspecialchars($_POST['name'],ENT_QUOTES);
	$email = htmlspecialchars($_POST['email'],ENT_QUOTES);
	$phone_number = htmlspecialchars($_POST['phone_number'],ENT_QUOTES);	
	$password = randomRefferalCode();

	//Check Sponsor Detail
	$sponsor_code_search = $sponsor_code;
	if (strpos($sponsor_code, 'MGP1') === 0 && $sponsor_code != 'MGP10000') {
		$sponsor_code_search = 'MG'.substr($sponsor_code, 3);
	}
	else if (strpos($sponsor_code, 'MG1') === 0) {
		$sponsor_code_search = 'MGP'.substr($sponsor_code, 2);
	}

	$sql_check_sponsor_detail = "SELECT * FROM user 
	WHERE (ref_code='$sponsor_code' OR ref_code='$sponsor_code_search')
	and status = '1'
	ORDER BY FIELD(ref_code, '$sponsor_code', '$sponsor_code_search')
	LIMIT 1 ";
	$result_check_sponsor_detail = $mysqli-> query($sql_check_sponsor_detail);
	if ($result_check_sponsor_detail -> num_rows > 0)
	{
		$row_check_sponsor_detail = $result_check_sponsor_detail ->fetch_assoc();
		$sponsor_id = $row_check_sponsor_detail['id'];
		$sponsor_ref_code = $row_check_sponsor_detail['ref_code'];
		$sponsor_code = $sponsor_ref_code;
		$sponsor_email = $row_check_sponsor_detail['email'];
		$sponsor_name = $row_check_sponsor_detail['name'];
	}
	else
	{
	  echo "<script type='text/javascript'>alert('This Sponsor ID not exist.Please try again');</script>";
      echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
      exit();
	}

	if ($sponsor_ref_code == '') 
	{
		echo "<script type='text/javascript'>alert('Fail. Please input the right Sponsor Referral ID');</script>";
		echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}

	//Check existing email
    $sql_check_email = "SELECT * FROM user 
	WHERE email='$email' 
	and status = '1'
	LIMIT 1";
	$result_check_email = $mysqli-> query($sql_check_email);
	if ($result_check_email -> num_rows > 0)
	{
		$row_check_email = $result_check_email ->fetch_assoc();
		echo "<script type='text/javascript'>alert('This email already being registered before. Please use other email');</script>";
        echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}

	$package_sale_code = randomRefferalCode();

	$cash_wallet = 0 ;
	$product_wallet = 0 ;
	$status = 1 ;
	$level  = 2 ; 

	//Select Lowest Type Of Rank For New Agent
	$sql_lowest_level = "SELECT * FROM user_level 
	WHERE status='1'
	Order by level_number Desc
	LIMIT 1";
	$result_lowest_level = $mysqli-> query($sql_lowest_level);
	if ($result_lowest_level -> num_rows > 0)
	{
		$row_lowest_level = $result_lowest_level ->fetch_assoc();
		$rank = $row_lowest_level['level_number'];
		$type_of_user = $row_lowest_level['level_name'];

	}
  
	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$word = "Success Registration.Please check your email in 24 hours for registration detail";	

	$New_ref_code_count = 1;
	$New_ref_code = "MG10001";

	$sql_last_user = "SELECT ref_code FROM user
	                  Where status='1'
					  And level='2'
					  And (
						  ref_code Like 'MG1%'
						  Or ref_code Like 'MGP1%'
					  )
					  And ref_code != 'MGP10000'
		              Order by CAST(REPLACE(REPLACE(ref_code, 'MGP1000', ''), 'MG1000', '') AS UNSIGNED) Desc
					  LIMIT 1 ";
	$result_last_user = $mysqli-> query($sql_last_user);
	if ($result_last_user -> num_rows > 0)
	{
		$row_last_user = $result_last_user ->fetch_assoc();
		$Last_ref_code = $row_last_user['ref_code'];
		$Last_ref_code = preg_replace('/^MGP?1000/', '', $Last_ref_code);
		$New_ref_code_count = (int)$Last_ref_code + 1;
		$New_ref_code = "MG1000".$New_ref_code_count;
	}

	//Check Upah Keyin
	$sql_sponsor_upah = "SELECT * FROM user_level
	WHERE level_number='$sponsor_rank' 
	and status ='1' LIMIT 1";
	$result_sponsor_upah = $mysqli-> query($sql_sponsor_upah);
	if ($result_sponsor_upah -> num_rows > 0)
	{
		$row_sponsor_upah = $result_sponsor_upah ->fetch_assoc();
		$upah_keyin = $row_sponsor_upah['upah_keyin'];
	}


	//Check Keyin Charge
	$sql_keyin_charge = "SELECT * FROM keyin_charge
	WHERE status='1' LIMIT 1";
	$result_keyin_charge = $mysqli-> query($sql_keyin_charge);
	if ($result_keyin_charge -> num_rows > 0)
	{
		$row_keyin_charge = $result_keyin_charge ->fetch_assoc();
		$keyin_charge = $row_keyin_charge['charge'];
	}

	//Check Sponsor Wallet
	$sql_sponsor_wallet = "SELECT * FROM wallet
	WHERE ref_code='$sponsor_code' LIMIT 1";
	$result_sponsor_wallet = $mysqli-> query($sql_sponsor_wallet);
	if ($result_sponsor_wallet -> num_rows > 0)
	{
		$row_sponsor_wallet = $result_sponsor_wallet ->fetch_assoc();
		$sponsor_cash_wallet = $row_sponsor_wallet['cash_wallet'];
	}

	$type_wallet = 'e_wallet' ;

	if ( $type_wallet == 'e_wallet')
	{
	     $my_wallet = $sponsor_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_wallet == 'gold_wallet')
	{
	     $my_wallet = $sponsor_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }

	$sponsor_new_wallet_keyin = $my_wallet - $keyin_charge;

	if ( $sponsor_new_wallet_keyin < '0')
	{   
	    $mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail. You dont have enough balance');</script>";
		echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	}
	else
	{
	    $sponsor_new_wallet = $sponsor_new_wallet_keyin + $upah_keyin;
	}

	$mysqli->begin_transaction();

	$Update_sponsor_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$sponsor_new_wallet'
	WHERE ref_code ='$sponsor_code'";
	$resUpdate_sponsor_wallet = $mysqli->query($Update_sponsor_wallet);

	$trans_code = randomRefferalCode();
	$trans_code_ARP_transaction = randomRefferalCode();

	if ( $resUpdate_sponsor_wallet ) 
	{
	    //Insert Keyin Charge transaction first
		$KC_status = '1';
		$KC_in_transactions = '0';
		$KC_out_transactions = $keyin_charge ;
		$KC_description = "Keyin Charge RM $keyin_charge " ;
		$KC_balance = $sponsor_new_wallet_keyin;
		$KC_type_of_transaction = $type_of_transaction ;

		$query_sponsor_transactions_KC  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$sponsor_code',
		'$trans_code',
		'$type_of_transaction',
		'$KC_in_transactions',
		'$KC_out_transactions',
		'$KC_balance',
		'$KC_description',
		'$KC_status',
		'$created_date'
		)";
		$res_sponsor_transactions_KC = $mysqli->query($query_sponsor_transactions_KC);

		/************************************************************************************************************************************/

		//Insert Upah Keyin transaction second
		$UP_status = '1';
		$UP_in_transactions = $upah_keyin;
		$UP_out_transactions = '0' ;
		$UP_description = "Upah Keyin $New_ref_code RM $keyin_charge " ;
		$UP_balance = $sponsor_new_wallet;
		$UP_type_of_transaction = $type_of_transaction ;

		$query_sponsor_transactions_KC  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$sponsor_code',
		'$trans_code',
		'$type_of_transaction',
		'$UP_in_transactions',
		'$UP_out_transactions',
		'$UP_balance',
		'$UP_description',
		'$UP_status',
		'$created_date'
		)";
		$res_sponsor_transactions_KC = $mysqli->query($query_sponsor_transactions_KC);
    }

	//Insert downline detail into User table
	$query_user  = " INSERT INTO user
	(
	level,
	rank,
	type_of_user,
	ref_code,
	sponsor_id,
	sponsor_code, 
	email,
	password,
	name,
	phone_number,
	status,
	created_date
	)
	VALUES
	(
	'$level',
	'$rank',
	'$type_of_user',
	'$New_ref_code',
	'$sponsor_id',
	'$sponsor_code',
	'$email',
	'$password',
	'$name',
	'$phone_number',
	'$status',
	'$created_date'
	)";
	$res_user = $mysqli->query($query_user);
	
		
	//Insert downline wallet detail into wallet table
	$query_wallet  = " INSERT INTO wallet
	(
	ref_code,	
	cash_wallet,
	product_wallet,
	created_date
	)
	VALUES
	(
	'$New_ref_code',
	'$cash_wallet',
	'$product_wallet',
	'$created_date'
	)";
	$res_wallet = $mysqli->query($query_wallet);
	

	  
	if ( $res_user && $res_wallet) 
	{
		$mysqli->commit();

		/************************************************************** Mail To Agent Start *************************************/

		$to  = $Email;
        $subject = "Hi $name, mygoldsdnbhd.com Account Verification";
        
        $message = "
		<html>
		<head>
		<title>Hi $name, mygoldsdnbhd.com Account Verification</title>
		</head>
		<body>
		<p>

		Hai $name,<br><br>

		Thank you for your registration as  $type_of_user<br>
		This is your account info<br><br>

		Name : $name <br>
		Email : $email <br>
		Password : $password <br>
		</p>

		</body>
		</html>
		";
        
        // Always set content-type when sending HTML email
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
		// More headers
		$headers .= 'From: <NoReply@mygoldsdnbhd.com>' . "\r\n";
		$headers .= "Reply-To: NoReply@mygoldsdnbhd.com\r\n";
		$headers .= "Return-Path: NoReply@mygoldsdnbhd.com\r\n";
		$headers .= "CC: NoReply@mygoldsdnbhd.com\r\n";
		$headers .= "BCC: NoReply@mygoldsdnbhd.com\r\n";
		mail($to, $subject, $message, $headers);

		echo "<script type='text/javascript'>alert('Registration Success');</script>";
        echo "<script type='text/javascript'> document.location='$page_success'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail');</script>";
		echo "<script type='text/javascript'> document.location='$page_fail'; </script>";
		exit();
	} 
}
?>

<?php
if (isset($_POST['Add_Ticket'])) 
{	
	$ref_code = $_POST['ref_code'];

	$subject1 = $_POST['subject'];
	$subject  = htmlspecialchars($subject1, ENT_QUOTES);

	$priority = $_POST['priority'];
	$category = $_POST['category'];

	$comment1 = $_POST['comment'];
	$comment  = htmlspecialchars($comment1, ENT_QUOTES);

	$status = 0 ;
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_support  = "INSERT INTO support_ticket
	(
	ref_code, 
	subject,	
	priority,
	category,
	comment,
	status, 
	created_date
	)
	VALUES
	(
	'$ref_code', 
	'$subject',	
	'$priority',
	'$category',
	'$comment',	
	'$status', 
	'$created_date'
	)";		
	$result_support = $mysqli->query($query_support);

	$sql_last_ticket = "SELECT id 
	                    FROM support_ticket
					    Where status='1'					    
					    Order by id Desc
					    LIMIT 1 ";
	$result_last_ticket = $mysqli-> query($sql_last_ticket);
	if ($result_last_ticket -> num_rows > 0)
	{
		$row_last_ticket = $result_last_ticket ->fetch_assoc();
		$Last_id = $row_last_ticket['id'];
	}

	if($result_support)
	{
		$mysqli->commit();

		/********************** Email To Admin *************************************************/
		$email_admin = 'syukranarpan@gmail.com';
		$name_admin = 'HQ';

		$to_admin      = $email_admin;
		$subject_admin = "mygoldsdnbhd.com New Support Ticket Info SPT00$Last_id";
        
		$message_admin = "
		<html>
		<head>
		<title>Hi $name_admin, There is New Support Ticket That Need Your Response</title>
		</head>
		<body>
		<p>

		Support Ticket ID : SPT00$Last_id<br>

		</p>

		</body>
		</html>
		";       
		// Always set content-type when sending HTML email
		$headers_admin .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
		$headers_admin .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
		$headers_admin .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
		mail($to_admin, $subject_admin, $message_admin, $headers_admin);
		/********************** Email To Admin *************************************************/

		/********************** SMS To Admin Start*************************************************/
		$message = "RM0 UMRAH HAJI MABRUR SDN BHD: New Support Ticket Info SPT00$Last_id";
		$hq_phone_number = "60102663796";

		$curl = curl_init();
		$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
		$params = array(
		'username' => 'mygoldplt_websystemmabrur',
		'password' => 'mygoldplt_websystemmabrur123',
		'message' => $message,
		'mobile' => $hq_phone_number,
		'Sender' => 'Test',
		'type' => '1'
		);
		$url = $endpoint . '?' . http_build_query($params);
		curl_setopt($curl, CURLOPT_URL, $url);

		$result = curl_exec($curl);
		$info = curl_getinfo($curl);  
		curl_close($curl);
		$obj = json_decode($result);

		//echo "<script type='text/javascript'>alert('$result);</script>";
		/********************** SMS To User End*************************************************/

		echo "<script type='text/javascript'>alert('Successfully Create New Ticket');</script>";
		echo "<script type='text/javascript'> document.location='../U/create_ticket.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/create_ticket.php'; </script>";
	}
}
?>


<?php
if (isset($_GET['form_name_Delete_User'])=='Delete_User') 
{
	$id = $_GET['id'];
	$ref_code = $_GET['ref_code'];
	$activation_status = $_GET['activation_status'];
	$mysqli->begin_transaction();

	$status_delete = '9';

	$Delete_user = "Delete from user
	WHERE id='$id' ";               
	$result_delete_user = $mysqli->query($Delete_user);

	$Delete_wallet = "Delete from wallet
	WHERE ref_code='$ref_code' ";               
	$result_delete_wallet = $mysqli->query($Delete_wallet);
    
	/*
	$UpdateQuery= "UPDATE user SET  
	status='$status_delete'
	WHERE id='$id' ";               
	$result_Delete = $mysqli->query($UpdateQuery);
	*/

	if($result_delete_user && $result_delete_wallet)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete User');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?activation_status=$activation_status'; </script>";		  
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?activation_status=$activation_status'; </script>";	  
	}     
}
?>

<?php
if (isset($_GET['form_name_Delete_Active_User'])=='Delete_Active_User') 
{
	$id = $_GET['id'];
	$ref_code = $_GET['ref_code'];
	$trans_code = $_GET['trans_code'];
	$activation_status = $_GET['activation_status'];
	$mysqli->begin_transaction();

	$status_delete = '9';

	$Delete_user = "Delete from user
	WHERE ref_code='$ref_code' ";               
	$result_delete_user = $mysqli->query($Delete_user);

	$Delete_wallet = "Delete from wallet
	WHERE ref_code='$ref_code' ";               
	$result_delete_wallet = $mysqli->query($Delete_wallet);

	$Delete_payment = "Delete from payment
	WHERE trans_code='$trans_code' ";               
	$result_delete_payment = $mysqli->query($Delete_payment);

	$Delete_package = "Delete from package_payment
	WHERE ref_code='$ref_code' ";               
	$result_delete_package = $mysqli->query($Delete_package);

	$Delete_woocommerce_order = "Delete from woocommerce_order_info
	WHERE new_ref_code='$ref_code' ";               
	$result_delete_woocommerce_order = $mysqli->query($Delete_woocommerce_order);

	$Delete_woocommerce_item = "Delete from woocommerce_order_info_item
	WHERE ref_code='$ref_code' ";               
	$result_delete_woocommerce_item = $mysqli->query($Delete_woocommerce_item);

	if($result_delete_user && $result_delete_wallet && $result_delete_payment && $result_delete_package && $result_delete_woocommerce_order && $result_delete_woocommerce_item)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete User');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?activation_status=$activation_status'; </script>";		  
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_user.php?activation_status=$activation_status'; </script>";	  
	}     
}
?>


<?php
if (isset($_POST['Add_Announcement'])) 
{	
    $announcement_ref_code = randomRefferalCode();
	$announcement_title  = htmlspecialchars($_POST['announcement_title'], ENT_QUOTES);
	$announcement_content  = htmlspecialchars($_POST['announcement_content'], ENT_QUOTES);

	$status = 1 ; 
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	$query_annouce  = "INSERT INTO announcement
	(
	announcement_ref_code,
	announcement_title,	
	announcement_content,
	status, 
	created_date
	)
	VALUES
	(
	'$announcement_ref_code',
	'$announcement_title',	
	'$announcement_content',
	'$status', 
	'$created_date'
	)";		
	$result_annouce = $mysqli->query($query_annouce);

	if ($_FILES['announcement_image']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["announcement_image"]["name"]);
		$newfilename1 = $announcement_ref_code . $time_stamp. '1.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{

			$check1 = getimagesize($_FILES["announcement_image"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["announcement_image"]["tmp_name"], $target_file1)  )
			{
				$announcement_image = $announcement_ref_code . $time_stamp. '1.' . end($temp1);

				$UpdateQuery = "UPDATE announcement SET 
				announcement_image='$announcement_image'
				WHERE announcement_ref_code='$announcement_ref_code' ";
				$result = $mysqli->query($UpdateQuery);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/add_announcement.php'; </script>";
				exit();
			}
		}
	}

	if($result_annouce)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Add New Announcement');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_announcement_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_announcement_1.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Announcement'])) 
{	
    $announcement_id  = htmlspecialchars($_POST['announcement_id'], ENT_QUOTES);
	$announcement_ref_code  = htmlspecialchars($_POST['announcement_ref_code'], ENT_QUOTES);
    $announcement_title  = htmlspecialchars($_POST['announcement_title'], ENT_QUOTES);
	$announcement_content  = htmlspecialchars($_POST['announcement_content'], ENT_QUOTES);

	$status = 1 ; 
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

   	$mysqli->begin_transaction();

	if ($_FILES['announcement_image']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["announcement_image"]["name"]);
		$newfilename1 = $announcement_ref_code . $time_stamp. '1.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{

			$check1 = getimagesize($_FILES["announcement_image"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["announcement_image"]["tmp_name"], $target_file1)  )
			{
				$announcement_image = $announcement_ref_code . $time_stamp. '1.' . end($temp1);

				$UpdateQuery = "UPDATE announcement SET 
				announcement_image='$announcement_image'
				WHERE announcement_ref_code='$announcement_ref_code' ";
				$result = $mysqli->query($UpdateQuery);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/add_announcement.php'; </script>";
				exit();
			}
		}
	}

	$UpdateQuery= "UPDATE announcement SET 
	announcement_title ='$announcement_title',
	announcement_content ='$announcement_content'
	WHERE id='$announcement_id' ";               
	$result_annouce = $mysqli->query($UpdateQuery);

	if($result_annouce)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Announcement');</script>";
		echo "<script type='text/javascript'> document.location='../U/update_announcement.php?id=$announcement_id'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/update_announcement.php?id=$announcement_id'; </script>";
	}
}
?>

<?php
if (isset($_GET['form_name_Delete_Announcement'])=='Delete_Announcement') 
{
	$announcement_id  = htmlspecialchars($_GET['announcement_id'], ENT_QUOTES);
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE announcement SET  
	status='9'
	WHERE id='$announcement_id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully delete announcement');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_announcement_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_announcement_1.php'; </script>";
	}        
}
?>

<?php
if (isset($_POST['Add_Promotion']))
{
    $promotion_ref_code = randomRefferalCode();
    $promotion_month = htmlspecialchars($_POST['promotion_month'], ENT_QUOTES);
    $promotion_year  = htmlspecialchars($_POST['promotion_year'], ENT_QUOTES);
    $promotion_title = htmlspecialchars($_POST['promotion_title'], ENT_QUOTES);
    $promotion_content = htmlspecialchars($_POST['promotion_content'], ENT_QUOTES);

    $status = 1;
    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d');

    $mysqli->begin_transaction();

    $query = "INSERT INTO monthly_promotion
    (
        promotion_ref_code,
        promotion_month,
        promotion_year,
        promotion_title,
        promotion_content,
        status,
        created_date
    )
    VALUES
    (
        '$promotion_ref_code',
        '$promotion_month',
        '$promotion_year',
        '$promotion_title',
        '$promotion_content',
        '$status',
        '$created_date'
    )";
    $result = $mysqli->query($query);

    if ($_FILES['promotion_image']['size'] != 0 )
    {
        $target_dir = "../Controller/uploads/";
        $time_stamp = time();
        $temp1 = explode(".", $_FILES["promotion_image"]["name"]);
        $newfilename1 = $promotion_ref_code . $time_stamp . '1.' . end($temp1);
        $target_file1 = $target_dir . basename($newfilename1);
        $uploadOk = 1;
        $imageFileType1 = pathinfo($target_file1, PATHINFO_EXTENSION);

        if (file_exists($target_file1)) {
            $uploadOk = 0;
        }

        if ($uploadOk == 1)
        {
            if (move_uploaded_file($_FILES["promotion_image"]["tmp_name"], $target_file1))
            {
                $promotion_image = $promotion_ref_code . $time_stamp . '1.' . end($temp1);

                $UpdateQuery = "UPDATE monthly_promotion SET
                                promotion_image='$promotion_image'
                                WHERE promotion_ref_code='$promotion_ref_code'";
                $mysqli->query($UpdateQuery);
            }
            else
            {
                $mysqli->rollback();
                echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
                echo "<script type='text/javascript'> document.location='../U/add_promotion.php'; </script>";
                exit();
            }
        }
    }

    if ($result)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Add New Promotion');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_promotion_1.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_promotion_1.php'; </script>";
    }
}
?>

<?php
if (isset($_POST['Update_Promotion']))
{
    $promotion_id = htmlspecialchars($_POST['promotion_id'], ENT_QUOTES);
    $promotion_ref_code = htmlspecialchars($_POST['promotion_ref_code'], ENT_QUOTES);
    $promotion_month = htmlspecialchars($_POST['promotion_month'], ENT_QUOTES);
    $promotion_year  = htmlspecialchars($_POST['promotion_year'], ENT_QUOTES);
    $promotion_title = htmlspecialchars($_POST['promotion_title'], ENT_QUOTES);
    $promotion_content = htmlspecialchars($_POST['promotion_content'], ENT_QUOTES);

    $mysqli->begin_transaction();

    if ($_FILES['promotion_image']['size'] != 0 )
    {
        $target_dir = "../Controller/uploads/";
        $time_stamp = time();
        $temp1 = explode(".", $_FILES["promotion_image"]["name"]);
        $newfilename1 = $promotion_ref_code . $time_stamp . '1.' . end($temp1);
        $target_file1 = $target_dir . basename($newfilename1);
        $uploadOk = 1;

        if (file_exists($target_file1)) {
            $uploadOk = 0;
        }

        if ($uploadOk == 1)
        {
            if (move_uploaded_file($_FILES["promotion_image"]["tmp_name"], $target_file1))
            {
                $promotion_image = $promotion_ref_code . $time_stamp . '1.' . end($temp1);

                $UpdateImg = "UPDATE monthly_promotion SET
                              promotion_image='$promotion_image'
                              WHERE promotion_ref_code='$promotion_ref_code'";
                $mysqli->query($UpdateImg);
            }
            else
            {
                $mysqli->rollback();
                echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
                echo "<script type='text/javascript'> document.location='../U/update_promotion.php?id=$promotion_id'; </script>";
                exit();
            }
        }
    }

    $UpdateQuery = "UPDATE monthly_promotion SET
                    promotion_month='$promotion_month',
                    promotion_year='$promotion_year',
                    promotion_title='$promotion_title',
                    promotion_content='$promotion_content'
                    WHERE id='$promotion_id'";
    $result = $mysqli->query($UpdateQuery);

    if ($result)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Update Promotion');</script>";
        echo "<script type='text/javascript'> document.location='../U/update_promotion.php?id=$promotion_id'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/update_promotion.php?id=$promotion_id'; </script>";
    }
}
?>

<?php
if (isset($_GET['form_name_Delete_Promotion']) == 'Delete_Promotion')
{
    $promotion_id = htmlspecialchars($_GET['promotion_id'], ENT_QUOTES);

    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE monthly_promotion SET
                    status='9'
                    WHERE id='$promotion_id'";
    $result = $mysqli->query($UpdateQuery);

    if ($result)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully delete promotion');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_promotion_1.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_promotion_1.php'; </script>";
    }
}
?>


<?php
if (isset($_POST['update_withdraw_detail'])) 
{	
    $withdraw_id  = htmlspecialchars($_POST['withdraw_id'], ENT_QUOTES);
	$shipping_selection  = htmlspecialchars($_POST['shipping_selection'], ENT_QUOTES);
	$name  = htmlspecialchars($_POST['name'], ENT_QUOTES);
	$last_name  = htmlspecialchars($_POST['last_name'], ENT_QUOTES);
	$phone_number  = htmlspecialchars($_POST['phone_number'], ENT_QUOTES);
	$country  = htmlspecialchars($_POST['country'], ENT_QUOTES);
	$state  = htmlspecialchars($_POST['state'], ENT_QUOTES);
	$postcode  = htmlspecialchars($_POST['postcode'], ENT_QUOTES);
	$shipping_address  = htmlspecialchars($_POST['shipping_address'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE withdraw_transaction SET 
	shipping_selection ='$shipping_selection',
	name ='$name',
	last_name ='$last_name',
	phone_number ='$phone_number',
	country ='$country',
	state ='$state',
	postcode ='$postcode',
	shipping_address ='$shipping_address'
	WHERE id='$withdraw_id' ";               
	$result_withdraw_detail = $mysqli->query($UpdateQuery);

	if($result_withdraw_detail)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Detail');</script>";
		echo "<script type='text/javascript'> document.location='../U/withdraw_detail.php?withdraw_id=$withdraw_id'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/update_announcement.php?id=$announcement_id'; </script>";
	}
}
?>

<?php
if (isset($_POST['upload_package_receipt'])) 
{   
    $ref_code = $_POST['ref_code'];	
    $purchase_code = $_POST['purchase_code'];
	$package_price = $_POST['package_price'];
	$package_name = $_POST['package_name'];
	$remark = $_POST['remark'];
	$payment_type = 'manual';

	$status = 0 ; 
	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');
    
	$mysqli->begin_transaction();
    
    if ($_FILES['receipt_upload']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["receipt_upload"]["name"]);
		$newfilename1 = $purchase_code . $time_stamp. '.' . end($temp1);
		$target_file1 = $target_dir . basename($newfilename1);
		$uploadOk = 1;
		$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

		// Check if image file is a actual image or fake image
		if(isset($_POST["submit"]))
		{
			$check1 = getimagesize($_FILES["receipt_upload"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
			}
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["receipt_upload"]["tmp_name"], $target_file1)  )
			{
				$receipt_upload = $purchase_code . $time_stamp. '.' . end($temp1);

				$query_payment  = "INSERT INTO payment
				(
				payment_code,
				ref_code,	
				attachment_image,
				payment_type,
				amount,
				order_remark,
				status, 
				created_date
				)
				VALUES
				(
				'$purchase_code',
				'$ref_code',	
				'$receipt_upload',
				'$payment_type',
				'$package_price',
				'$remark',
				'$status', 
				'$created_date'
				)";		
				$result_payment = $mysqli->query($query_payment);
	
	            //Update package sale info
				$UpdateQuery = "UPDATE package_sale SET  
				status='2'
				WHERE purchase_code='$purchase_code' ";
				$result = $mysqli->query($UpdateQuery);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../U/purchase_package_payment_manual.php?purchase_code=$purchase_code&package_name=$package_name&package_price=$package_price'; </script>";
				exit();
			}
		}
	}
    if ($result) 
	{	    
		$mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully upload receipt');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_purchase.php'; </script>";
		exit();
    }   
    else 
	{   
	    $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail. Please try again');</script>";
        echo "<script type='text/javascript'> document.location='../U/list_of_purchase.php'; </script>";
		exit();
    } 
}
?>


<?php
if (isset($_POST['change_sponsor'])) 
{
	$ref_code= $_POST['ref_code'];
	$tree_sponsor_code= $_POST['tree_sponsor_code'];

	//Check New Tree Sponsor Detail
	$sql_check_sponsor_detail = "SELECT * FROM user 
	WHERE ref_code='$tree_sponsor_code'
	And status='1'";
	$result_check_sponsor_detail = $mysqli-> query($sql_check_sponsor_detail);
	if ($result_check_sponsor_detail -> num_rows > 0)
	{
		$row_check_sponsor_detail = $result_check_sponsor_detail ->fetch_assoc();
		$sponsor_ref_code = $row_check_sponsor_detail['ref_code'];
	    $sponsor_email = $row_check_sponsor_detail['email'];
	    $sponsor_name = $row_check_sponsor_detail['name'];
	    $sponsor_no_of_downline = $row_check_sponsor_detail['no_of_downline'];
	}

	if ( $sponsor_no_of_downline >= 5 )
	//Check if new tree sponsor already got 5 then cannot add anymore
	{
	    echo "<script type='text/javascript'>alert('Fail. This User already got 5 Direct Tree Downline.Please choose other user');</script>";
        echo "<script type='text/javascript'> document.location='../U/change_sponsor.php?ref_code=$ref_code '; </script>";
	}
	else
	// if new tree sponsor already got less than 5 then can add
	{	
		//Check Sponsor Detail
		$sql_find_sponsor = "SELECT * FROM user
		WHERE ref_code='$tree_sponsor_code'
		And status='1'
		LIMIT 1";		
		$result_find_sponsor = $mysqli-> query($sql_find_sponsor);
		if ($result_find_sponsor -> num_rows > 0)
		{
			$row_find_sponsor = $result_find_sponsor ->fetch_assoc();
			$sponsor_code = $row_find_sponsor['ref_code'];
			$sponsor_ref_code = $row_find_sponsor['ref_code'];
			$sponsor_email = $row_find_sponsor['email'];
			$sponsor_name = $row_find_sponsor['name'];
			$sponsor_no_of_downline = $row_find_sponsor['no_of_downline'];
			$sponsor_left_1_pairing_status = $row_find_sponsor['left_1_pairing_status'];
			$sponsor_left_2_pairing_status = $row_find_sponsor['left_2_pairing_status'];
			$sponsor_middle_pairing_status = $row_find_sponsor['middle_pairing_status'];
			$sponsor_right_1_pairing_status = $row_find_sponsor['right_1_pairing_status'];
			$sponsor_right_2_pairing_status = $row_find_sponsor['right_2_pairing_status'];
		}

		$sponsor_new_no_of_downline = $sponsor_no_of_downline + 1 ; //Tambah 1 dekat no of downline sponsor

		if ( $sponsor_left_1_pairing_status == 0)
		{
			$pairing_position = "L1";
			$sponsor_left_1_pairing_ref_code = $ref_code;
			$sponsor_pairing_status_coloumn = "left_1_pairing_status";
			$sponsor_pairing_ref_code_coloumn = "left_1_pairing_ref_code";
		}
		else
		if ( $sponsor_left_2_pairing_status == 0)
		{
			$pairing_position = "L2";
			$sponsor_left_2_pairing_ref_code = $ref_code;
			$sponsor_pairing_status_coloumn = "left_2_pairing_status";
			$sponsor_pairing_ref_code_coloumn = "left_2_pairing_ref_code";
		}
		else
		if ( $sponsor_middle_pairing_status == 0)
		{
			$pairing_position = "M";
			$sponsor_middle_pairing_ref_code = $ref_code;
			$sponsor_pairing_status_coloumn = "middle_pairing_status";
			$sponsor_pairing_ref_code_coloumn = "middle_pairing_ref_code";
		}
		else
		if ( $sponsor_right_1_pairing_status == 0)
		{
			$pairing_position = "R1";
			$sponsor_right_1_pairing_ref_code = $ref_code;
			$sponsor_pairing_status_coloumn = "right_1_pairing_status";
			$sponsor_pairing_ref_code_coloumn = "right_1_pairing_ref_code";
		}
		else
		if ( $sponsor_right_2_pairing_status == 0)
		{
			$pairing_position = "R2";
			$sponsor_right_2_pairing_ref_code = $ref_code;
			$sponsor_pairing_status_coloumn = "right_2_pairing_status";
			$sponsor_pairing_ref_code_coloumn = "right_2_pairing_ref_code";
		}

		//Update Sponsor Tree Detail
		$Update_Sponsor_Detail = "UPDATE user SET   
		$sponsor_pairing_status_coloumn ='1' ,
		$sponsor_pairing_ref_code_coloumn = '$ref_code' ,
		no_of_downline = '$sponsor_new_no_of_downline'
		WHERE ref_code ='$tree_sponsor_code'";
		$resUpdate_Sponsor_Detail = $mysqli->query($Update_Sponsor_Detail);
		
		//Update New Sponsor
		$Update_new_tree_sponsor = "UPDATE user SET
		tree_sponsor_code='$tree_sponsor_code'
		WHERE ref_code = '$ref_code' ";
		$result_new_tree_sponsor = $mysqli->query($Update_new_tree_sponsor);
	}


    if ($resUpdate_Sponsor_Detail && $result_new_tree_sponsor) 
	{
        $mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully updated new tree sponsor');</script>";
        echo "<script type='text/javascript'> document.location='../U/change_sponsor.php?ref_code=$ref_code '; </script>";
		exit();
    }   
    else 
	{
        $mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail. Please try again');</script>";
        echo "<script type='text/javascript'> document.location='../U/change_sponsor.php?ref_code=$ref_code '; </script>";
		exit();
    }  
}
?>

<?php
if (isset($_POST['deposit']))
{  
    $type_wallet = $_POST['type_wallet'];
	$deposit_way = $_POST['deposit_way'];
	$amount = $_POST['amount'];
	$deposit_fees_usdt_percent = $_POST['deposit_fees_usdt_percent'];
	$total_deposit_need_to_transfer = $_POST['total_deposit_need_to_transfer'];
	$ref_code  = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
    $trx_ref  = htmlspecialchars($_POST['trx_ref'], ENT_QUOTES);
	$payment_reference  = htmlspecialchars($_POST['payment_reference'], ENT_QUOTES);

    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

	$sql_password = "SELECT * FROM user 
    WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_password = $mysqli-> query($sql_password);
	if ($result_password -> num_rows > 0)
	{
		$row_password = $result_password ->fetch_assoc();
		$password_user = $row_password['password'];
		$name_user = $row_password['name'];
		$email_user = $row_password['email'];
	}

	$sql_curr_rate = "SELECT *
				      FROM currency_rate_setting
				      Where status='1'
				      order by id Asc";
	$result_curr_rate = $mysqli-> query($sql_curr_rate);
	if ($result_curr_rate -> num_rows > 0)
	{
		$row_curr_rate = $result_curr_rate ->fetch_assoc();
		$deposit_rm = $row_curr_rate['deposit_rm'];
	}

	$mysqli->begin_transaction();

	$trans_code = randomRefferalCode();

	if ($deposit_way == "FPX")
	{
	    $amount_MYR = $amount * $withdrawal_rm;
		$fees = 0;
	}
	else
	if ($deposit_way == "PayPal")
	{
	    $amount_MYR = $amount * $withdrawal_rm;
		$fees = 0;
	}
	else
	if ($deposit_way == "Upload_Receipt")
	{
	    $amount_MYR = $amount * $withdrawal_rm;
		$fees = 0;
	}
	else
	if ($deposit_way == "USDT")
	{
	    $amount_MYR = $total_deposit_need_to_transfer * $withdrawal_rm;
		$fees = ($deposit_fees_usdt_percent/100) * $amount;

		$type_of_transaction = "CW";
		$hq_ref_code = "MGP10000";
		$status_hq = '1';
		$in_transactions_hq = $fees;
		$out_transactions_hq = 0 ;
		$description_hq = "Deposit Fees $fees " ;
		$type_of_transaction_hq = $type_of_transaction ;
		$type_of_process_hq = "HQ Deposit Fees";

		//HQ deposit fees
		$query_hq_deposit_charge  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$hq_ref_code',
		'$trans_code',
		'$type_of_process_hq',
		'$type_of_transaction_hq',
		'$in_transactions_hq',
		'$out_transactions_hq',
		'$description_hq',
		'$status_hq',
		'$created_date'
		)";
		$res_hq_deposit_charge = $mysqli->query($query_hq_deposit_charge);
	}
	
	$type_of_transaction = "PW";
	$status = '1';
	$deposit_status = '0';
	$in_transactions = $amount;
	$out_transactions = 0 ;
	$description = "Deposit To Activation Wallet $$amount " ;
	$type_of_transaction = $type_of_transaction ;
	$type_of_process = "Member Deposit To Activation Wallet";

	//Insert Deposit Transactions
	$query_deposit  = " INSERT INTO transactions
	(
	deposit_way,
	user_ref_code,
	trans_code,
	type_of_process,
	type_of_transaction,
	in_transactions,
	out_transactions,
	description,
	trx_ref,
	fees,
	deposit_status,
	status,
	created_date
	)
	VALUES
	(
	'$deposit_way',
	'$ref_code',
	'$trans_code',
	'$type_of_process',
	'$type_of_transaction',
	'$in_transactions',
	'$out_transactions',
	'$description',
	'$trx_ref',
	'$fees',
	'$deposit_status',
	'$status',
	'$created_date'
	)";
	$res_deposit = $mysqli->query($query_deposit);

	//If upload receipt do this
	if ($deposit_way == "Upload_Receipt")
	{
	    if ($_FILES['receipt_upload']['size'] != 0 )
		{
			$target_dir = "../Controller/uploads/";
			$time_stamp = time();
			$temp1 = $temp1 = explode(".", $_FILES["receipt_upload"]["name"]);
			$newfilename1 = $trans_code . $time_stamp. '.' . end($temp1);
			$target_file1 = $target_dir . basename($newfilename1);
			$uploadOk = 1;
			$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

			// Check if image file is a actual image or fake image
			if(isset($_POST["submit"]))
			{
				$check1 = getimagesize($_FILES["receipt_upload"]["tmp_name"]);
				if( ($check1 !== false) )
				{
					echo "File is an Image - " . $check1["mime"] . ".";
					$uploadOk = 1;
				} 
				else 
				{
					echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
					$uploadOk = 0;
				}
			}

			// Check if file already exists
			if ( (file_exists($target_file1)) )
			{
				echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
				$uploadOk = 0;
			}

			// Check if $uploadOk is set to 0 by an error
			if ($uploadOk == 0)
			{
				echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
				// if everything is ok, try to upload file
			}
			else
			{
				if ( move_uploaded_file($_FILES["receipt_upload"]["tmp_name"], $target_file1)  )
				{
					$receipt_upload = $trans_code . $time_stamp. '.' . end($temp1);

					//Update package sale info
					$UpdateQuery = "UPDATE transactions SET  
					receipt_upload='$receipt_upload',
					payment_reference='$payment_reference'
					WHERE trans_code='$trans_code' ";
					$result = $mysqli->query($UpdateQuery);
				}
				else
				{
					echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
					echo "<script type='text/javascript'> document.location='../U/wallet_deposit.php'; </script>";
					exit();
				}
			}
		}
	}

	if ($res_deposit) 						    
	{
		$mysqli->commit();

		if ($deposit_way == "FPX")
		{
			echo "<script type='text/javascript'> document.location='../U/checkout_proceed_B_payment_deposit_toyyibpay.php?user_ref_code=$ref_code&trans_code=$trans_code'; </script>";
		}
		else
		if ($deposit_way == "PayPal")
		{
			echo "<script type='text/javascript'> document.location='../U/checkout_proceed_B_payment_deposit_paypal.php?user_ref_code=$ref_code&trans_code=$trans_code'; </script>";
		}
		else
		if ($deposit_way == "Upload_Receipt")
		{
			/********************** Email To HQ *************************************************/
			$hq_email = "syukranarpan@gmail.com";
			$to_hq = $hq_email;
			$subject_hq = "Hi $hq_email, mygoldsdnbhd.com New Deposit Request";
        
			$message_hq = "
			<html>
			<head>
			<title>Hi $hq_email, mygoldsdnbhd.com Account New Deposit Request</title>
			</head>
			<body>
			<p>

			Hai $hq_email,<br><br>

			mygoldsdnbhd.com New Deposit Request from $ref_code | $email_user  <br><br>
			</p>

			</body>
			</html>
			";
        
			// Always set content-type when sending HTML email
			$headers_hq = "MIME-Version: 1.0" . "\r\n";
			$headers_hq .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
			// More headers
			$headers_hq .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
			$headers_hq .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
			$headers_hq .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
			mail($to_hq, $subject_hq, $message_hq, $headers_hq);
		   /********************** Email To HQ *************************************************/

		   /********************** SMS To Admin Start*************************************************/
			$message = "RM0 UMRAH HAJI MABRUR SDN BHD: mygoldsdnbhd.com New Deposit Request from $ref_code | $email_user";
			$hq_phone_number = "60102663796";

			$curl = curl_init();
			$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
			$params = array(
			'username' => 'mygoldplt_websystemmabrur',
			'password' => 'mygoldplt_websystemmabrur123',
			'message' => $message,
			'mobile' => $hq_phone_number,
			'Sender' => 'Test',
			'type' => '1'
			);
			$url = $endpoint . '?' . http_build_query($params);
			curl_setopt($curl, CURLOPT_URL, $url);

			$result = curl_exec($curl);
			$info = curl_getinfo($curl);  
			curl_close($curl);
			$obj = json_decode($result);

			//echo "<script type='text/javascript'>alert('$result);</script>";
			/********************** SMS To User End*************************************************/
		
		    echo "<script type='text/javascript'>alert('Thank you. Your deposit request will be process ASAP');</script>";
		    echo "<script type='text/javascript'> document.location='../U/wallet_deposit_history.php?type_wallet=e_wallet'; </script>";
		}
		else
		if ($deposit_way == "USDT")
		{
			/********************** Email To HQ *************************************************/
			$hq_email = "syukranarpan@gmail.com";
			$to_hq = $hq_email;
			$subject_hq = "Hi $hq_email, mygoldsdnbhd.com New Deposit Request";
        
			$message_hq = "
			<html>
			<head>
			<title>Hi $hq_email, mygoldsdnbhd.com Account New Deposit Request</title>
			</head>
			<body>
			<p>

			Hai $hq_email,<br><br>

			mygoldsdnbhd.com New Deposit Request from $ref_code | $email_user  <br><br>
			</p>

			</body>
			</html>
			";
        
			// Always set content-type when sending HTML email
			$headers_hq = "MIME-Version: 1.0" . "\r\n";
			$headers_hq .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
			// More headers
			$headers_hq .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
			$headers_hq .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
			$headers_hq .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
			mail($to_hq, $subject_hq, $message_hq, $headers_hq);
		   /********************** Email To HQ *************************************************/

		   /********************** SMS To Admin Start*************************************************/
			$message = "RM0 UMRAH HAJI MABRUR SDN BHD: mygoldsdnbhd.com New Deposit Request from $ref_code | $email_user";
			$hq_phone_number = "60102663796";

			$curl = curl_init();
			$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
			$params = array(
			'username' => 'mygoldplt_websystemmabrur',
			'password' => 'mygoldplt_websystemmabrur123',
			'message' => $message,
			'mobile' => $hq_phone_number,
			'Sender' => 'Test',
			'type' => '1'
			);
			$url = $endpoint . '?' . http_build_query($params);
			curl_setopt($curl, CURLOPT_URL, $url);

			$result = curl_exec($curl);
			$info = curl_getinfo($curl);  
			curl_close($curl);
			$obj = json_decode($result);

			//echo "<script type='text/javascript'>alert('$result);</script>";
			/********************** SMS To User End*************************************************/
		
		    echo "<script type='text/javascript'>alert('Thank you. Your deposit request will be process ASAP');</script>";
		    echo "<script type='text/javascript'> document.location='../U/wallet_deposit_history.php?type_wallet=e_wallet'; </script>";
		}
		
		exit();
	}
	else
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail to Withdraw');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
		exit();
	}

}
?>


<?php
if (isset($_GET['form_name_Approve_Deposit'])=='Approve_Deposit') 
{
    $trans_code = $_GET['trans_code'];
    $ref_code = $_GET['ref_code'];

	$mysqli->begin_transaction();

	/********************************************************** Mamber Transaction Part Start Here *******************************/
	//Get amount of deposit
	$sql_my_transactions = "SELECT * 
	FROM transactions
	WHERE trans_code='$trans_code' 
	And type_of_transaction='PW' 
	LIMIT 1";
	$result_my_transactions = $mysqli-> query($sql_my_transactions);
	if ($result_my_transactions -> num_rows > 0)
	{
		$row_my_transactions = $result_my_transactions ->fetch_assoc();
		$my_deposit_amount = $row_my_transactions['in_transactions'];
	}

	//Members Wallet
    $sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_product_wallet = $row_my_wallet['product_wallet'];
	}

	$my_new_wallet = $my_product_wallet + $my_deposit_amount;
	
	//Update member wallet
	$Update_my_wallet = "UPDATE wallet SET   
	product_wallet ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	$Update_my_transaction = "UPDATE transactions SET   
	balance = '$my_new_wallet',
	deposit_status = '1'
	WHERE trans_code ='$trans_code'";
	$resUpdate_my_transaction = $mysqli->query($Update_my_transaction);

	/********************************************************** Mamber Transaction Part End Here *******************************/

	/********************************************************** HQ Transaction Part Start Here *******************************/
	//Check if got Deposit Fees
	$sql_hq_transactions = "SELECT * 
	FROM transactions
	WHERE trans_code='$trans_code' 
	And type_of_transaction = 'CW' 
	LIMIT 1";
	$result_hq_transactions = $mysqli-> query($sql_hq_transactions);
	if ($result_hq_transactions -> num_rows > 0)
	{
		$row_hq_transactions = $result_hq_transactions ->fetch_assoc();
		$deposit_fees = $row_hq_transactions['in_transactions'];
	}

	if ($deposit_fees != "")
	{
		//HQ Wallet
		$hq_ref_code = "MGP10000";

		$sql_hq_wallet = "SELECT * FROM wallet
		WHERE ref_code='$hq_ref_code' LIMIT 1";
		$result_hq_wallet = $mysqli-> query($sql_hq_wallet);
		if ($result_hq_wallet -> num_rows > 0)
		{
			$row_hq_wallet = $result_hq_wallet ->fetch_assoc();
			$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
		}

		$hq_new_wallet = $hq_cash_wallet + $deposit_fees;

		//Update HQ wallet
		$Update_hq_wallet = "UPDATE wallet SET   
		cash_wallet ='$hq_new_wallet'
		WHERE ref_code ='$hq_ref_code'";
		$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

		$Update_hq_transaction = "UPDATE transactions SET   
		balance = '$hq_new_wallet',
		deposit_status = '1'
		WHERE trans_code ='$trans_code'";
		$resUpdate_hq_transaction = $mysqli->query($Update_hq_transaction);
	}
	/********************************************************** HQ Transaction Part End Here *******************************/
   
   	if($resUpdate_my_wallet && $resUpdate_my_transaction)
   	{		  
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Approve Deposit User');</script>";
		echo "<script type='text/javascript'>document.location='../U/wallet_deposit_history.php?type_wallet=a_wallet'; </script>";	  
   	}
   	else 	  
   	{		  
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_deposit_history.php?type_wallet=a_wallet'; </script>";	   
    }
}
?>

<?php
if (isset($_GET['form_name_Reject_Deposit'])=='Reject_Deposit') 
{
    $trans_code = $_GET['trans_code'];
    $ref_code = $_GET['ref_code'];

	$mysqli->begin_transaction();

	$Update_my_transaction = "UPDATE transactions SET   
	status = '9'
	WHERE trans_code ='$trans_code'";
	$resUpdate_my_transaction = $mysqli->query($Update_my_transaction);
   
   	if($resUpdate_my_transaction)
   	{		  
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Reject Deposit Request');</script>";
		echo "<script type='text/javascript'>document.location='../U/wallet_deposit_history.php?type_wallet=a_wallet'; </script>";	  
   	}
   	else 	  
   	{		  
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_deposit_history.php?type_wallet=a_wallet'; </script>";	   
    }
}
?>


<?php
if (isset($_POST['withdraw']))
{
    $type_wallet   = $_POST['type_wallet'];
    $amount        = (float)$_POST['amount'];
    $withdraw_type = $_POST['withdraw_way'];

    $ref_code = htmlspecialchars($_POST['ref_code'], ENT_QUOTES);
    $acc_holder_name = htmlspecialchars($_POST['acc_holder_name'] ?? '', ENT_QUOTES);
    $acc_no = $_POST['acc_no'] ?? '';
    $bank   = $_POST['bank'] ?? '';
    $blockchain_address = $_POST['blockchain_address'] ?? '';

    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date     = date('Y-m-d');
    $created_datetime = date('Y-m-d H:i:s');
    $today            = date('Y-m-d');

    //Withdraw only on 1st & 16th for e_wallet
    $todayDay = (int)date('j');
    $isWithdrawDay = in_array($todayDay, [1, 16], true);

    if ($type_wallet == 'e_wallet' && !$isWithdrawDay) {
        echo "<script type='text/javascript'>alert('Withdrawal is only allowed on 1st and 16th day of the current month.');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }

    // e_wallet max USD 1000 per day (existing logic)
    if ($type_wallet == 'e_wallet') {
        $data_total_withdraw = "
            SELECT SUM(amount) As num
            FROM withdraw_transaction
            WHERE ref_code ='$ref_code'
              AND tac_verify_status  = '1'
              AND created_date = '$today'
        ";
        $result_total_withdraw = $mysqli->query($data_total_withdraw);
        $total_withdraw = 0;
        if ($result_total_withdraw && $result_total_withdraw->num_rows > 0) {
            $row_total_withdraw = $result_total_withdraw->fetch_assoc();
            $total_withdraw = (float)($row_total_withdraw['num'] ?? 0);
        }

        if ($total_withdraw > 1000 || $amount > 1000 || ($total_withdraw + $amount) > 1000) {
            echo "<script type='text/javascript'>alert('Fail. Max withdrawal is USD 1000 per day');</script>";
            echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
            exit();
        }
    }

    // Get user info (for email/hq notification, existing checks)
    $sql_user = "SELECT * FROM user WHERE ref_code='$ref_code' AND status='1' LIMIT 1";
    $result_user = $mysqli->query($sql_user);
    if (!$result_user || $result_user->num_rows == 0) {
        echo "<script type='text/javascript'>alert('Fail. User not found');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }
    $row_user = $result_user->fetch_assoc();
    $email_user = $row_user['email'];
    $phone_number_user = $row_user['phone_number'];

    // If withdraw to bank need bank info
    if ($withdraw_type == "bank") {
        if ($acc_holder_name == "" || $acc_no == "" || $bank == "") {
            echo "<script type='text/javascript'>alert('Fail. Please update your bank info at profile page before withdraw');</script>";
            echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
            exit();
        }
        $blockchain_address = "";
    }

    // Currency + fees
    $sql_curr_rate = "SELECT * FROM currency_rate_setting WHERE status='1' ORDER BY id ASC LIMIT 1";
    $result_curr_rate = $mysqli->query($sql_curr_rate);
    if (!$result_curr_rate || $result_curr_rate->num_rows == 0) {
        echo "<script type='text/javascript'>alert('Fail. Currency setting not found');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }
    $row_curr_rate = $result_curr_rate->fetch_assoc();
    $withdrawal_rm = (float)$row_curr_rate['withdrawal_rm'];
    $withdraw_charge = (float)$row_curr_rate['withdraw_fees_usd'];
    $withdraw_fees_usdt_percent = (float)$row_curr_rate['withdraw_fees_usdt_percent'];

    if ($withdraw_type == "bank") {
        $withdraw_fees = $withdraw_charge;
    } else if ($withdraw_type == "usdt") {
        $withdraw_fees = (float)($amount * ($withdraw_fees_usdt_percent/100));
        $acc_holder_name = "";
        $acc_no = "";
        $bank = "";
    } else {
        // fallback
        $withdraw_fees = $withdraw_charge;
    }

    $amount_MYR = (float)($amount * $withdrawal_rm);

    // Wallet rows
    $sql_my_wallet = "SELECT * FROM wallet WHERE ref_code='$ref_code' LIMIT 1";
    $result_my_wallet = $mysqli->query($sql_my_wallet);
    if (!$result_my_wallet || $result_my_wallet->num_rows == 0) {
        echo "<script type='text/javascript'>alert('Fail. Wallet not found');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }
    $row_my_wallet = $result_my_wallet->fetch_assoc();
    $my_cash_wallet = (float)($row_my_wallet['cash_wallet'] ?? 0);
    $my_pins_wallet = (float)($row_my_wallet['pins_wallet'] ?? 0);
    $my_product_wallet = (float)($row_my_wallet['product_wallet'] ?? 0);

    if ($type_wallet == 'e_wallet') {
        $my_wallet = $my_cash_wallet;
        $wallet_column_name = "cash_wallet";
        $type_of_transaction = "CW";
        $word_success = "Succesfully Withdraw. Please wait 3-5 days for approval (Exclude Saturday & Sunday)";
    } else if ($type_wallet == 'pins_wallet') {
        $my_wallet = $my_pins_wallet;
        $wallet_column_name = "pins_wallet";
        $type_of_transaction = "DW";
        $word_success = "Succesfully Withdraw. Please wait 7-14 days for approval (Exclude Saturday & Sunday)";
    } else if ($type_wallet == 'gold_wallet') {
        $my_wallet = $my_product_wallet;
        $wallet_column_name = "product_wallet";
        $type_of_transaction = "PW";
        $word_success = "Succesfully Withdraw. Please wait for approval.";
    } else {
        echo "<script type='text/javascript'>alert('Fail. Invalid wallet type');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }

    // New balance after withdraw + fees
    $my_new_wallet = (float)number_format($my_wallet - $amount - $withdraw_fees, 2, '.', '');

    if ($my_new_wallet < 0) {
        echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }

    // HQ wallet
    $hq_ref_code = "MGP10000";
    $sql_hq_wallet = "SELECT * FROM wallet WHERE ref_code='$hq_ref_code' LIMIT 1";
    $result_hq_wallet = $mysqli->query($sql_hq_wallet);
    if (!$result_hq_wallet || $result_hq_wallet->num_rows == 0) {
        echo "<script type='text/javascript'>alert('Fail. HQ wallet not found');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }
    $row_hq_wallet = $result_hq_wallet->fetch_assoc();
    $hq_cash_wallet = (float)($row_hq_wallet['cash_wallet'] ?? 0);
    $hq_new_wallet = (float)number_format($hq_cash_wallet + $withdraw_fees, 2, '.', '');

    // Start DB TX (single flow, no OTP)
    $mysqli->begin_transaction();

    $withdraw_trans_code = randomRefferalCode(); // use as withdraw_transaction.trans_code AND HQ txn trans_code

    // 1) Insert HQ withdraw fees transaction (keep same behavior)
    $description_hq = "Withdraw Fees $$withdraw_fees";
    $query_hq_withdraw_charge = "INSERT INTO transactions
    (
        user_ref_code, trans_code, type_of_process, type_of_transaction,
        in_transactions, out_transactions, description, status, created_date
    )
    VALUES
    (
        '$hq_ref_code', '$withdraw_trans_code', 'HQ Withdraw Fees', '$type_of_transaction',
        '$withdraw_fees', '0', '$description_hq', '1', '$created_datetime'
    )";
    $res_hq_withdraw_charge = $mysqli->query($query_hq_withdraw_charge);

    // 2) Insert withdraw_transaction ( auto verified, no OTP page)
    $withdraw_to = "BA";
    $query_withdraw_transaction = "INSERT INTO withdraw_transaction
    (
        trans_code, ref_code, tac_no, withdraw_to, type_of_transaction,
        amount, amount_MYR, withdraw_fees,
        acc_holder_name, acc_no, bank, blockchain_address,
        payment_status, status, created_date, created_datetime,
        tac_verify_status, balance
    )
    VALUES
    (
        '$withdraw_trans_code', '$ref_code', '', '$withdraw_to', '$type_of_transaction',
        '$amount', '$amount_MYR', '$withdraw_fees',
        '$acc_holder_name', '$acc_no', '$bank', '$blockchain_address',
        '0', '0', '$created_date', '$created_datetime',
        '1', '$my_new_wallet'
    )";
    $res_withdraw_transaction = $mysqli->query($query_withdraw_transaction);

    // 3) Update member wallet
    $Update_my_wallet = "UPDATE wallet SET $wallet_column_name='$my_new_wallet' WHERE ref_code='$ref_code'";
    $resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

    // 4) Update HQ wallet
    $Update_hq_wallet = "UPDATE wallet SET cash_wallet='$hq_new_wallet' WHERE ref_code='$hq_ref_code'";
    $resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

    // 5) Update HQ transaction balance to latest
    $Update_hq_transaction = "UPDATE transactions SET balance='$hq_new_wallet' WHERE trans_code='$withdraw_trans_code'";
    $resUpdate_hq_transaction = $mysqli->query($Update_hq_transaction);

    if ($res_hq_withdraw_charge && $res_withdraw_transaction && $resUpdate_my_wallet && $resUpdate_hq_wallet && $resUpdate_hq_transaction) {
        $mysqli->commit();

        //notify HQ (reuse your existing email/SMS block from withdraw_confirm)
        $hq_email = "syukranarpan@gmail.com";
        $to_hq = $hq_email;
        $subject_hq = "Hi $hq_email, mygoldsdnbhd.com New Withdraw Request";
        $message_hq = "
        <html><body><p>
        Hai $hq_email,<br><br>
        mygoldsdnbhd.com New Withdraw Request from $ref_code<br><br>
        </p></body></html>";
        $headers_hq  = "MIME-Version: 1.0\r\n";
        $headers_hq .= "Content-type:text/html;charset=UTF-8\r\n";
        $headers_hq .= "From: <no-reply@mygoldsdnbhd.com>\r\n";
        $headers_hq .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
        $headers_hq .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
        @mail($to_hq, $subject_hq, $message_hq, $headers_hq);

        // optional SMS admin (keep if you want)
        // ... (same SMS code you already have) ...

        echo "<script type='text/javascript'>alert('$word_success');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_history.php?type_wallet=$type_wallet&status=0'; </script>";
        exit();
    } else {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail to Withdraw');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet.php?type_wallet=$type_wallet'; </script>";
        exit();
    }
}
?>


<?php
if (isset($_POST['withdraw_confirm']))
{  
    $withdraw_trans_code = $_POST['withdraw_trans_code'];
	$tac_no = $_POST['tac_no'];
	$type_wallet = $_POST['type_wallet'];

	$sql_withdraw = "SELECT * 
	FROM withdraw_transaction
	WHERE trans_code='$withdraw_trans_code' LIMIT 1";
	$result_withdraw = $mysqli-> query($sql_withdraw);
	if ($result_withdraw -> num_rows > 0)
	{
		$row_withdraw = $result_withdraw ->fetch_assoc();
		$ref_code = $row_withdraw['ref_code'];
		$tac_no_system = $row_withdraw['tac_no'];
		$amount = $row_withdraw['amount'];
		$withdraw_fees = $row_withdraw['withdraw_fees'];
	}
	
	if ( $tac_no != $tac_no_system)
	{   
	    echo "<script type='text/javascript'>alert('Wrong TAC No. Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_tack_no.php?withdraw_trans_code=$withdraw_trans_code'; </script>";
		exit();
	}

	$sql_my_wallet = "SELECT * 
	FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_cash_wallet = $row_my_wallet['cash_wallet'];
		$my_pins_wallet = $row_my_wallet['pins_wallet'];
	}

	$hq_ref_code = "MGP10000";

	$sql_hq_wallet = "SELECT * 
	FROM wallet
	WHERE ref_code='$hq_ref_code' LIMIT 1";
	$result_hq_wallet = $mysqli-> query($sql_hq_wallet);
	if ($result_hq_wallet -> num_rows > 0)
	{
		$row_hq_wallet = $result_hq_wallet ->fetch_assoc();
		$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
	}

	if ( $type_wallet == 'e_wallet')
	{
		 $my_wallet = $my_cash_wallet;
		 $hq_wallet = $hq_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
		 $word_success = "Succesfully Withdraw.Please wait 3-5 days for approval (Exclude Saturday & Sunday)";
	}
	else
	if ( $type_wallet == 'pins_wallet')
	{
		 $my_wallet = $my_pins_wallet;
		 $hq_wallet = $hq_cash_wallet;
		 $wallet_column_name ="pins_wallet";
		 $type_of_transaction = "DW";
		 $word_success = "Succesfully Withdraw.Please wait 7-14 days for approval (Exclude Saturday & Sunday)";
	}

	$amount = $amount + $withdraw_fees ; 
	$my_new_wallet = $my_wallet - $amount;

	$hq_new_wallet = $hq_wallet + $withdraw_fees;
	
	$mysqli->begin_transaction();

	if ($my_new_wallet < 0 || $my_new_wallet < 0.00)
	{   
		$mysqli->rollback();
	    echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_tack_no.php?withdraw_trans_code=$withdraw_trans_code'; </script>";
		exit();
	}

	//Update member wallet
	$Update_my_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	//Update HQ wallet
	$Update_hq_wallet = "UPDATE wallet SET   
	cash_wallet ='$hq_new_wallet'
	WHERE ref_code ='$hq_ref_code'";
	$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

	$Update_transaction = "UPDATE withdraw_transaction SET   
	balance = '$my_new_wallet',
	tac_verify_status = '1'
	WHERE trans_code ='$withdraw_trans_code'";
	$resUpdate_transaction = $mysqli->query($Update_transaction);

	$Update_hq_transaction = "UPDATE transactions SET   
	balance = '$hq_new_wallet'
	WHERE trans_code ='$withdraw_trans_code'";
	$resUpdate_hq_transaction = $mysqli->query($Update_hq_transaction);

	if ( $resUpdate_my_wallet && $resUpdate_hq_wallet && $resUpdate_transaction && $resUpdate_hq_transaction) 
	{
		$mysqli->commit();

		/********************** Email To HQ *************************************************/
			$hq_email = "syukranarpan@gmail.com";
			$to_hq = $hq_email;
			$subject_hq = "Hi $hq_email, mygoldsdnbhd.com New Withdraw Request";
        
			$message_hq = "
			<html>
			<head>
			<title>Hi $hq_email, mygoldsdnbhd.com Account New Withdraw Request</title>
			</head>
			<body>
			<p>

			Hai $hq_email,<br><br>

			mygoldsdnbhd.com New Withdraw Request from $ref_code <br><br>
			</p>

			</body>
			</html>
			";
        
			// Always set content-type when sending HTML email
			$headers_hq = "MIME-Version: 1.0" . "\r\n";
			$headers_hq .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        
			// More headers
			$headers_hq .= 'From: <no-reply@mygoldsdnbhd.com>' . "\r\n";
			$headers_hq .= "Reply-To: no-reply@mygoldsdnbhd.com\r\n";
			$headers_hq .= "Return-Path: no-reply@mygoldsdnbhd.com\r\n";
			mail($to_hq, $subject_hq, $message_hq, $headers_hq);
		/********************** Email To HQ *************************************************/

		/********************** SMS To Admin Start*************************************************/
		$message = "RM0 UMRAH HAJI MABRUR SDN BHD: mygoldsdnbhd.com New Withdraw Request from $ref_code";
		$hq_phone_number = "60102663796";

		$curl = curl_init();
		$endpoint = 'http://www.sms.bulksms2u.com/websmsapi/ISendSMS.aspx';
		$params = array(
		'username' => 'mygoldplt_websystemmabrur',
		'password' => 'mygoldplt_websystemmabrur123',
		'message' => $message,
		'mobile' => $hq_phone_number,
		'Sender' => 'Test',
		'type' => '1'
		);
		$url = $endpoint . '?' . http_build_query($params);
		curl_setopt($curl, CURLOPT_URL, $url);

		$result = curl_exec($curl);
		$info = curl_getinfo($curl);  
		curl_close($curl);
		$obj = json_decode($result);

		//echo "<script type='text/javascript'>alert('$result);</script>";
		/********************** SMS To User End*************************************************/

		echo "<script type='text/javascript'>alert('$word_success');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_history.php?type_wallet=$type_wallet&status=0'; </script>";
		exit();
	}
	else
	{
	    $mysqli->rollback();
	    echo "<script type='text/javascript'>alert('Fail to Update your wallet');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_tack_no.php?withdraw_trans_code=$withdraw_trans_code'; </script>";
		exit();
	}
}
?>


<?php
if (isset($_POST['Reset_Database_Setting'])) 
{
   	$mysqli->begin_transaction();

	$Delete_package_sale = "Delete from package_sale
	WHERE id !='' ";               
	$result_delete_package_sale = $mysqli->query($Delete_package_sale);

	$Delete_payment = "Delete from payment
	WHERE id !='' ";               
	$result_payment = $mysqli->query($Delete_payment);

	$Delete_transactions = "Delete from transactions
	WHERE id !='' ";               
	$result_transactions = $mysqli->query($Delete_transactions);

	$Delete_withdraw_transactions = "Delete from withdraw_transaction
	WHERE id !='' ";               
	$result_withdraw_transactions = $mysqli->query($Delete_withdraw_transactions);

	$Update_wallet= "UPDATE wallet SET  
	cash_wallet='0', 
	product_wallet='0'
	WHERE id !='' ";               
	$result_wallet = $mysqli->query($Update_wallet);

	$Update_hq_wallet= "UPDATE wallet SET  
	cash_wallet='0', 
	product_wallet='100000000000'
	WHERE ref_code = 'MGP10000' ";               
	$result_hq_wallet = $mysqli->query($Update_hq_wallet);
	   
	if($result_delete_package_sale && $result_payment && $result_transactions && $result_withdraw_transactions && $result_wallet && $result_hq_wallet)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Reset');</script>";
		echo "<script type='text/javascript'> document.location='../U/reset_database.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/reset_database.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['topup_wallet']))
{
	$ref_code = htmlspecialchars($_POST['ref_code'],ENT_QUOTES);
	$type_wallet = htmlspecialchars($_POST['type_wallet'],ENT_QUOTES);
	$amount = htmlspecialchars($_POST['amount'],ENT_QUOTES);
	$password = htmlspecialchars($_POST['password'],ENT_QUOTES);

	date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

	$sql_password = "SELECT * FROM user 
    WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_password = $mysqli-> query($sql_password);
	if ($result_password -> num_rows > 0)
	{
		$row_password = $result_password ->fetch_assoc();
		$password_user = $row_password['password'];
	}
    
	if ( $password != $password_user)
	{
	    echo "<script type='text/javascript'>alert('Wrong Password. Please enter the right password');</script>";
        echo "<script type='text/javascript'> document.location='../U/topup_wallet.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
	else
	{
		$trans_code = randomRefferalCode();
		$status = '0';
		$in_transactions = $amount;
		$out_transactions = 0 ;
		$description = "Top Up RM $amount " ;
		$type_of_transaction = 'CW' ;

		$query_my_transactions_cash_wallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_transaction,
		in_transactions,
		out_transactions,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$ref_code',
		'$trans_code',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$description',
		'$status',
		'$created_date'
		)";
		$res_my_transactions_cash_wallet = $mysqli->query($query_my_transactions_cash_wallet);
	}
	if ($res_my_transactions_cash_wallet)
	{
		echo "<script type='text/javascript'> document.location='../U/topup_wallet_payment.php?type_wallet=$type_wallet&amount=$amount&ref_code=$ref_code&trans_code=$trans_code'; </script>";
	}
	else
	{
	    echo "<script type='text/javascript'>alert('Fail');</script>";
        echo "<script type='text/javascript'> document.location='../U/topup_wallet.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
}
?>


<?php
if (isset($_POST['withdraw_transfer'])) 
{
    $type_wallet = $_POST['type_wallet'];
	$ori_tac_no = $_POST['ori_tac_no'];
	$tac_no = $_POST['tac_no'];
	$level = $_POST['level'];

	/*
	if ($level == "2")
    {
		if ($ori_tac_no != $tac_no)
		{
			echo "<script type='text/javascript'>alert('Wrong TAC No.');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
	}
	*/

	$ref_code1 = $_POST['ref_code'];
    $ref_code  = htmlspecialchars($ref_code1, ENT_QUOTES);

	$friend_ref_code1 = $_POST['friend_ref_code'];
    $friend_ref_code  = htmlspecialchars($friend_ref_code1, ENT_QUOTES);

	$sql_check_user = "SELECT * FROM user 
	WHERE ref_code ='$friend_ref_code' 
	And status ='1'";
	$result_check_user = $mysqli-> query($sql_check_user);
	if ($result_check_user -> num_rows == 0)
	{
		echo "<script type='text/javascript'>alert('This member not Exist. Please choose another member');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}

	$withdraw_to="BA";

    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');

	$sql_password = "SELECT * FROM user 
    WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_password = $mysqli-> query($sql_password);
	if ($result_password -> num_rows > 0)
	{
		$row_password = $result_password ->fetch_assoc();
		$password_user = $row_password['password'];
		$email_user = $row_password['email'];
		$level_user = $row_password['level'];
	}

	$password1 = $_POST['password'];
    $password  = htmlspecialchars($password1, ENT_QUOTES);
    
	if ( $password != $password_user)
	{
	    echo "<script type='text/javascript'>alert('Wrong Password. Please enter the right password');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
    
    $amount_1 = $_POST['amount'];
	$withdraw_charge = '0' ;
	$amount = $amount_1 - $withdraw_charge ; 

	// Check My Wallet
	$sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet  = $mysqli-> query($sql_my_wallet );
	if ($result_my_wallet  -> num_rows > 0)
	{
		$row_my_wallet  = $result_my_wallet  ->fetch_assoc();
		$my_cash_wallet = $row_my_wallet['cash_wallet'];
		$my_product_wallet = $row_my_wallet['product_wallet'];
	}

	if ( $type_wallet == 'e_wallet')
	{
	     $my_wallet = $my_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_wallet == 'a_wallet')
	{
	     $my_wallet = $my_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }

	$my_new_wallet = $my_wallet - $amount_1;

	if ( $my_new_wallet < '0')
	{   
	    echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}

	$mysqli->begin_transaction();

	$Update_my_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	// Check My Friend Wallet
	$sql_my_friend_wallet = "SELECT * FROM wallet
	WHERE ref_code='$friend_ref_code' LIMIT 1";
	$result_my_friend_wallet = $mysqli-> query($sql_my_friend_wallet);
	if ($result_my_friend_wallet -> num_rows > 0)
	{
		$row_my_friend_wallet = $result_my_friend_wallet ->fetch_assoc();
		$my_friend_cash_wallet = $row_my_friend_wallet['cash_wallet'];
		$my_friend_product_wallet = $row_my_friend_wallet['product_wallet'];
	}

	if ( $type_wallet == 'e_wallet')
	{
	     $my_friend_wallet = $my_friend_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_wallet == 'a_wallet')
	{
	     $my_friend_wallet = $my_friend_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }
	
	$my_new_friend_wallet = $my_friend_wallet + $amount_1;

	$Update_my_friend_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$my_new_friend_wallet'
	WHERE ref_code ='$friend_ref_code'";
	$resUpdate_my_friend_wallet = $mysqli->query($Update_my_friend_wallet);

	$trans_code = randomRefferalCode();
	$trans_code_ARP_transaction = randomRefferalCode();

	if ( $resUpdate_my_wallet ) 
	{
		$status = '1';
		$in_transactions = '0';
		$out_transactions = $amount_1 ;
		$description = "Transfer $ $amount To $friend_ref_code" ;
		$balance = $my_new_wallet;
		$type_of_transaction = $type_of_transaction ;
		$withdraw = "1";
		$withdraw_status = "1";

		if ($level_user == '1')
		{
		  $type_of_process = "HQ Transfer Activation Wallet";
		}
		else
		{
		  $type_of_process = "Member Transfer Activation Wallet";
		}
		
		$query_my_transactions_cash_wallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		withdraw,
		withdraw_status,
		status,
		created_date
		)
		VALUES
		(
		'$ref_code',
		'$trans_code',
		'$type_of_process',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$balance',
		'$description',
		'$withdraw',
		'$withdraw_status',
		'$status',
		'$created_date'
		)";
		$res_my_transactions_cash_wallet = $mysqli->query($query_my_transactions_cash_wallet);

		$status = '1';
		$in_transactions = $amount_1;
		$out_transactions = 0 ;
		$description = "Receive $ $amount from $ref_code" ;
		$balance = $my_new_friend_wallet;
		$type_of_transaction = $type_of_transaction ;
		$withdraw = "1";
		$withdraw_status = "1";
		$type_of_process_member = "Member Receive Activation Wallet";

		$query_my_friend_transactions_cash_wallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		withdraw,
		withdraw_status,
		status,
		created_date
		)
		VALUES
		(
		'$friend_ref_code',
		'$trans_code',
		'$type_of_process_member',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$balance',
		'$description',
		'$withdraw',
		'$withdraw_status',
		'$status',
		'$created_date'
		)";
		$res_my_friend_transactions_cash_wallet = $mysqli->query($query_my_friend_transactions_cash_wallet);

		if ( $res_my_transactions_cash_wallet &&  $res_my_friend_transactions_cash_wallet) 						    
		{
			$mysqli->commit();
			echo "<script type='text/javascript'>alert('A-Wallet Transfer Success');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
		else
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Fail to Transfer');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
	}
	else
	{
	    echo "<script type='text/javascript'>alert('Fail to Update your wallet');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
}
?>


<?php
if (isset($_POST['withdraw_e_transfer'])) 
{
	$type_wallet = $_POST['type_wallet'];
	$type_Of_wallet = $_POST['type_Of_wallet'];
	$amount_1 = $_POST['amount']; //8.00

	//Check Currency Rate
	$sql_curr_rate = "SELECT *
					  FROM currency_rate_setting
					  Where status='1'
					  order by id Asc";
					  $result_curr_rate = $mysqli-> query($sql_curr_rate);
	if ($result_curr_rate -> num_rows > 0)
	{
		$row_curr_rate = $result_curr_rate ->fetch_assoc();
		$deposit_rm = $row_curr_rate['deposit_rm'];
		$withdrawal_rm = $row_curr_rate['withdrawal_rm'];
		$withdraw_fees_usd = $row_curr_rate['withdraw_fees_usd'];
	}

	if ($type_Of_wallet == "e_wallet")
    {
        //$withdraw_charge = 0.1 * $amount_1 ; //0.80
        //$display_fees = "10%";

		$withdraw_charge = 0 ;
        $display_fees = "0%";
		$amount = $amount_1 - $withdraw_charge ;  //7.20
	}
    else
    if ($type_Of_wallet == "a_wallet")
    {
        //$withdraw_charge = 1.00 ;
        //$display_fees = "$1.00";

		$withdraw_charge = 0 ;
        $display_fees = "$0.00";
		$amount = $amount_1 - $withdraw_charge ;
		$amount_RM = $amount * $withdrawal_rm;
		$amount = $amount_RM/$deposit_rm;
	}
    
	$ref_code1 = $_POST['ref_code'];
    $ref_code  = htmlspecialchars($ref_code1, ENT_QUOTES);

	$friend_ref_code1 = $_POST['friend_ref_code'];
    $friend_ref_code  = htmlspecialchars($friend_ref_code1, ENT_QUOTES);

	//If from same wallet to same wallet, don't allow if within same member
	if ($type_Of_wallet == $type_wallet)
    {
		if ($ref_code == $friend_ref_code)
		{
			echo "<script type='text/javascript'>alert('Fail. Transfer from same $type_wallet to $type_Of_wallet within same member not allowed.');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
	}

	$sql_check_user = "SELECT * FROM user 
	WHERE ref_code ='$friend_ref_code' 
	And status ='1'";
	$result_check_user = $mysqli-> query($sql_check_user);
	if ($result_check_user -> num_rows == 0)
	{
		echo "<script type='text/javascript'>alert('This member not Exist. Please choose another member');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
	else
	{
		$row_check_user = $result_check_user ->fetch_assoc();
		$friend_name = $row_check_user['name'];
	}

	$withdraw_to="BA";

    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');


	$sql_password = "SELECT * FROM user 
    WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_password = $mysqli-> query($sql_password);
	if ($result_password -> num_rows > 0)
	{
		$row_password = $result_password ->fetch_assoc();
		$password_user = $row_password['password'];
		$email_user = $row_password['email'];
		$level_user = $row_password['level'];
	}

	$password1 = $_POST['password'];
    $password  = htmlspecialchars($password1, ENT_QUOTES);
    
	if ( $password != $password_user)
	{
	    echo "<script type='text/javascript'>alert('Wrong Password. Please enter the right password');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
    
	// Check My Wallet
	$sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_cash_wallet = $row_my_wallet['cash_wallet'];
		$my_product_wallet = $row_my_wallet['product_wallet'];
	}

	if ( $type_wallet == 'e_wallet')
	{
	     $my_wallet = $my_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_wallet == 'a_wallet')
	{
	     $my_wallet = $my_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }

	$my_new_wallet = $my_wallet - $amount_1;

	if ( $my_new_wallet < '0')
	{   
	    echo "<script type='text/javascript'>alert('Insufficient Balance');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}

	$mysqli->begin_transaction();

	$Update_my_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	// Check My Friend Wallet
	$sql_my_friend_wallet = "SELECT * FROM wallet
	WHERE ref_code='$friend_ref_code' LIMIT 1";
	$result_my_friend_wallet = $mysqli-> query($sql_my_friend_wallet);
	if ($result_my_friend_wallet -> num_rows > 0)
	{
		$row_my_friend_wallet = $result_my_friend_wallet ->fetch_assoc();
		$my_friend_cash_wallet = $row_my_friend_wallet['cash_wallet'];
		$my_friend_product_wallet = $row_my_friend_wallet['product_wallet'];	
	}

	if ( $type_Of_wallet == 'e_wallet')
	{
	     $my_friend_wallet = $my_friend_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_Of_wallet == 'a_wallet')
	{
	     $my_friend_wallet = $my_friend_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }
	
	$my_new_friend_wallet = $my_friend_wallet + $amount;

	$Update_my_friend_wallet = "UPDATE wallet SET   
	$wallet_column_name ='$my_new_friend_wallet'
	WHERE ref_code ='$friend_ref_code'";
	$resUpdate_my_friend_wallet = $mysqli->query($Update_my_friend_wallet);

	$trans_code = randomRefferalCode();
	$trans_code_ARP_transaction = randomRefferalCode();

	if ( $resUpdate_my_wallet ) 
	{
		$status = '1';
		$in_transactions = '0';
		$out_transactions = $amount_1 ;
		$description = "Transfer $ $amount To $friend_ref_code with $display_fees charge $ $withdraw_charge " ;
		$balance = $my_new_wallet;
		$type_of_transaction = $type_of_transaction ;
		$withdraw = "1";
		$withdraw_status = "1";

		if ($level_user == '1')
		{
		  $type_of_process = "HQ Transfer E-Wallet";
		}
		else
		{
		  $type_of_process = "Member Transfer E-Wallet";
		}
		
		$query_my_transactions_cash_wallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		withdraw,
		withdraw_status,
		status,
		created_date
		)
		VALUES
		(
		'$ref_code',
		'$trans_code',
		'$type_of_process',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$balance',
		'$description',
		'$withdraw',
		'$withdraw_status',
		'$status',
		'$created_date'
		)";
		$res_my_transactions_cash_wallet = $mysqli->query($query_my_transactions_cash_wallet);


		$status = '1';
		$in_transactions = $amount;
		$out_transactions = 0 ;
		$description = "Receive $ $amount from $ref_code" ;
		$balance = $my_new_friend_wallet;
		$type_of_transaction = $type_of_transaction ;
		$withdraw = "1";
		$withdraw_status = "1";
		$type_of_process_member = "Member Receive E-Wallet";

		$query_my_friend_transactions_cash_wallet  = " INSERT INTO transactions
		(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		withdraw,
		withdraw_status,
		status,
		created_date
		)
		VALUES
		(
		'$friend_ref_code',
		'$trans_code',
		'$type_of_process_member',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$balance',
		'$description',
		'$withdraw',
		'$withdraw_status',
		'$status',
		'$created_date'
		)";
		$res_my_friend_transactions_cash_wallet = $mysqli->query($query_my_friend_transactions_cash_wallet);


    /**************************************************************** HQ Transaction Start**********************************/
	if ($withdraw_charge > 0)
	{
		//Get HQ Wallet Info
		$hq_ref_code = "MGP10000";

		$sql_hq_wallet = "SELECT * 
		FROM wallet
		WHERE ref_code='$hq_ref_code' LIMIT 1";
		$result_hq_wallet = $mysqli-> query($sql_hq_wallet);
		if ($result_hq_wallet -> num_rows > 0)
		{
			$row_hq_wallet = $result_hq_wallet ->fetch_assoc();
			$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
		}

		$hq_new_wallet = $hq_cash_wallet + $withdraw_charge;

		$Update_hq_wallet = "UPDATE wallet SET   
		cash_wallet ='$hq_new_wallet'
		WHERE ref_code ='$hq_ref_code'";
		$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

		$hq_status = '1';
		$hq_in_transactions = $withdraw_charge;
		$hq_out_transactions = 0 ;
		$hq_description = "Transfer E-wallet Fees $$withdraw_charge" ;
		$hq_balance = $hq_new_wallet;
		$hq_type_of_transaction = 'CW' ;
		$type_of_process_hq = "HQ E-wallet transfer Fees";

		$query_fees_transaction  = " INSERT INTO transactions
		(
		trans_code,
		type_of_process,
		user_ref_code,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$trans_code',
		'$type_of_process_hq',
		'$hq_ref_code',
		'$hq_type_of_transaction',
		'$hq_in_transactions',
		'$hq_out_transactions',
		'$hq_balance',
		'$hq_description',
		'1',
		'$created_date'
		)";		
		$res_fees_transaction = $mysqli->query($query_fees_transaction);
	}
	/**************************************************************** HQ Transaction End**********************************/

		if ( $res_my_transactions_cash_wallet &&  $res_my_friend_transactions_cash_wallet) 				    
		{
			$mysqli->commit();
			echo "<script type='text/javascript'>alert('E-Wallet Transfer Success');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
		else
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Fail to Transfer');</script>";
			echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
			exit();
		}
	}
	else
	{
	    $mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail to Update your wallet');</script>";
        echo "<script type='text/javascript'> document.location='../U/wallet_transfer.php?type_wallet=$type_wallet'; </script>";
		exit();
	}
}
?>


<?php
if (isset($_GET['form_name_Approve_Withdraw'])=='Approve_Withdraw') 
{
   $trans_code = $_GET['trans_code'];
   $ref_code = $_GET['ref_code'];

   	//Get withdraw_transaction Info
	$sql_withdraw_info = "SELECT * 
	FROM withdraw_transaction
	WHERE trans_code='$trans_code' LIMIT 1";
	$result_withdraw_info = $mysqli-> query($sql_withdraw_info);
	if ($result_withdraw_info -> num_rows > 0)
	{
		$row_withdraw_info = $result_withdraw_info ->fetch_assoc();
		$withdraw_amount = $row_withdraw_info['amount'];
		$type_of_transaction = $row_withdraw_info['type_of_transaction'];
		$type_of_transaction = $row_withdraw_info['type_of_transaction'];
		$acc_holder_name = $row_withdraw_info['acc_holder_name'];
		$acc_no = $row_withdraw_info['acc_no'];
		$bank = $row_withdraw_info['bank'];
	}

	//Get User Wallet Info
	/*
	$sql_user_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_user_wallet = $mysqli-> query($sql_user_wallet);
	if ($result_user_wallet -> num_rows > 0)
	{
		$row_user_wallet = $result_user_wallet ->fetch_assoc();
		$user_cash_wallet = $row_user_wallet['cash_wallet'];
		$user_product_wallet = $row_user_wallet['product_wallet'];
	}
	*/

	//Get User Info
	$sql_user_info = "SELECT * FROM user
	WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_user_info = $mysqli-> query($sql_user_info);
	if ($result_user_info -> num_rows > 0)
	{
		$row_user_info = $result_user_info ->fetch_assoc();
		$user_email = $row_user_info['email'];
		$user_name = $row_user_info['ref_code'];
	}

	if ($type_of_transaction == 'CW')
	{
	     $type_wallet = "e_wallet";
	}
	else 
	if ($type_of_transaction == 'DW')
	{
	     $type_wallet = "pins_wallet";
    }

	/*
	if ( $type_of_transaction == 'CW')
	{
	     $my_wallet = $user_cash_wallet;
		 $wallet_column_name ="cash_wallet";
		 $type_of_transaction = "CW";
	}
	else 
	if ( $type_of_transaction == 'PW')
	{
	     $my_wallet = $user_product_wallet;
		 $wallet_column_name ="product_wallet";
		 $type_of_transaction = "PW";
    }

	$my_new_wallet = $my_wallet - $withdraw_amount;
			
	//Update user Wallet Info
	$Update_user_wallet = "UPDATE wallet SET
	$wallet_column_name ='$my_new_wallet'
	WHERE ref_code = '$ref_code' ";
	$result_user_wallet = $mysqli->query($Update_user_wallet);
	*/

	$UpdateQueryWT= "UPDATE withdraw_transaction SET  
   	payment_status='1'
   	WHERE trans_code='$trans_code' ";               
   	$resultWT = $mysqli->query($UpdateQueryWT);

	/*
	//Insert Transaction Detail For user
	$user_status = '1';
	$user_in_transactions = '0' ;
	$user_out_transactions = $withdraw_amount ;
	$user_description = "Payment USD $withdraw_amount To Your Bank Account $bank | $acc_holder_name | $acc_no" ;
	$user_balance = $my_new_wallet;
	$user_type_of_transaction = $type_of_transaction ;

	$query_transactions_cash_wallet_user  = " INSERT INTO transactions
	(
	user_ref_code,
	type_of_transaction,
	in_transactions,
	out_transactions,
	balance,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$ref_code',
	'$user_type_of_transaction',
	'$user_in_transactions',
	'$user_out_transactions',
	'$user_balance',
	'$user_description',
	'$user_status',
	'$created_date'
	)";
	$res_transactions_cash_wallet_user = $mysqli->query($query_transactions_cash_wallet_user);
	*/
   
   	if($resultWT )
   	{		  

	/********************** Email To user *************************************************/
	$email_user = $user_email;
	$name_user = $user_name;

	$to_user      = $email_user;
	$subject_user = "Hi " . $name_user . ",  Withdrawal USD$withdraw_amount has been successfully credited to your bank account.";
        
	$message_user = "
	<html>
	<head>
	<title>Hi " . $name_user . ",  Withdrawal USD$withdraw_amount has been successfully credited to your bank account.</title>
	</head>
	<body>
	<p>

	Hai ".$name_user.",<br><br>

	The withdrawal detail as below:<br><br>

	Amount : ".$withdraw_amount."<br>
	Bank : ".$bank."<br>
	Account No : ".$acc_no."<br>

	</p>

	</body>
	</html>
	";       
	// Always set content-type when sending HTML email
	$headers_user = "MIME-Version: 1.0" . "\r\n";
	$headers_user .= 'Content-type:text/html;charset=UTF-8' . "\r\n";        
	// More headers
	$headers_user .= 'From: <finance@mygoldsdnbhd.com >' . "\r\n";
	$headers_user .= "Reply-To: finance@mygoldsdnbhd.com \r\n";
	$headers_user .= "Return-Path: finance@mygoldsdnbhd.com \r\n";
	mail($to_user, $subject_user, $message_user, $headers_user);
	/********************** Email To user *************************************************/

	/********************** Email To SuperAdmin *************************************************/
	$email_superadmin = 'syukranarpan@gmail.com';
	$name_superadmin = 'HQ';

	$to_superadmin      = $email_superadmin;
	$subject_superadmin = "Hi " . $name_superadmin . ", Withdrawal USD$withdraw_amount has been successfully credited to $user_name |  $user_email";
        
	$message_superadmin = "
	<html>
	<head>
	<title>Hi " . $name_superadmin . ", Withdrawal USD$withdraw_amount has been successfully credited to $user_name |  $user_email</title>
	</head>
	<body>
	<p>

	Hai ".$name_superadmin.",<br><br>

	The withdrawal detail as below:<br><br>

	Amount : ".$withdraw_amount."<br>
	Bank : ".$bank."<br>
	Account No : ".$acc_no."<br>
	
	</p>

	</body>
	</html>
	";       
	// Always set content-type when sending HTML email
	$headers_superadmin = "MIME-Version: 1.0" . "\r\n";
	$headers_superadmin .= 'Content-type:text/html;charset=UTF-8' . "\r\n";        
	// More headers
	$headers_superadmin .= 'From: <finance@mygoldsdnbhd.com >' . "\r\n";
	$headers_superadmin .= "Reply-To: finance@mygoldsdnbhd.com \r\n";
	$headers_superadmin .= "Return-Path: finance@mygoldsdnbhd.com \r\n";
	mail($to_superadmin, $subject_superadmin, $message_superadmin, $headers_superadmin);
	/********************** Email To SuperAdmin *************************************************/


		echo "<script type='text/javascript'>alert('Succesfully Withdraw To User');</script>";
		echo "<script type='text/javascript'>document.location='../U/wallet_history.php?type_wallet=$type_wallet'; </script>";	  
   	}
   	else 	  
   	{		  
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_history.php?type_wallet=$type_wallet'; </script>";	   
    }
}
?>


<?php
if (isset($_POST['form_name_Approve_Withdraw_Bulk'])) 
{
   if(!empty($_POST['witdhraw_id']))
   {
		// Loop to store and display values of individual checked checkbox.
		foreach($_POST['witdhraw_id'] as $witdhraw_id)
		{
			//Get withdraw_transaction Info
			$sql_withdraw_info = "SELECT * 
			FROM withdraw_transaction
			WHERE id = '$witdhraw_id' LIMIT 1";
			$result_withdraw_info = $mysqli-> query($sql_withdraw_info);
			if ($result_withdraw_info -> num_rows > 0)
			{
				$row_withdraw_info = $result_withdraw_info ->fetch_assoc();
				$trans_code = $row_withdraw_info['trans_code'];
				$ref_code = $row_withdraw_info['ref_code'];
				$withdraw_amount = $row_withdraw_info['amount'];
				$type_of_transaction = $row_withdraw_info['type_of_transaction'];
				$type_of_transaction = $row_withdraw_info['type_of_transaction'];
				$acc_holder_name = $row_withdraw_info['acc_holder_name'];
				$acc_no = $row_withdraw_info['acc_no'];
				$bank = $row_withdraw_info['bank'];
			}

			//Get User Wallet Info
			/*
			$sql_user_wallet = "SELECT * FROM wallet
			WHERE ref_code='$ref_code' LIMIT 1";
			$result_user_wallet = $mysqli-> query($sql_user_wallet);
			if ($result_user_wallet -> num_rows > 0)
			{
				$row_user_wallet = $result_user_wallet ->fetch_assoc();
				$user_cash_wallet = $row_user_wallet['cash_wallet'];
				$user_product_wallet = $row_user_wallet['product_wallet'];
			}
			*/

			//Get User Info
			$sql_user_info = "SELECT * FROM user
			WHERE ref_code='$ref_code' 
			And status='1'
			LIMIT 1";
			$result_user_info = $mysqli-> query($sql_user_info);
			if ($result_user_info -> num_rows > 0)
			{
				$row_user_info = $result_user_info ->fetch_assoc();
				$user_email = $row_user_info['email'];
				$user_name = $row_user_info['ref_code'];
			}

			if ($type_of_transaction == 'CW')
			{
				 $type_wallet = "e_wallet";
			}
			else 
			if ($type_of_transaction == 'DW')
			{
				 $type_wallet = "pins_wallet";
			}

			/*
			if ( $type_of_transaction == 'CW')
			{
				 $my_wallet = $user_cash_wallet;
				 $wallet_column_name ="cash_wallet";
				 $type_of_transaction = "CW";
			}
			else 
			if ( $type_of_transaction == 'PW')
			{
				 $my_wallet = $user_product_wallet;
				 $wallet_column_name ="product_wallet";
				 $type_of_transaction = "PW";
			}

			$my_new_wallet = $my_wallet - $withdraw_amount;
			
			//Update user Wallet Info
			$Update_user_wallet = "UPDATE wallet SET
			$wallet_column_name ='$my_new_wallet'
			WHERE ref_code = '$ref_code' ";
			$result_user_wallet = $mysqli->query($Update_user_wallet);
			*/

			$UpdateQueryWT= "UPDATE withdraw_transaction SET  
   			payment_status='1'
   			WHERE trans_code='$trans_code' ";               
   			$resultWT = $mysqli->query($UpdateQueryWT);

			/*
			//Insert Transaction Detail For user
			$user_status = '1';
			$user_in_transactions = '0' ;
			$user_out_transactions = $withdraw_amount ;
			$user_description = "Payment USD $withdraw_amount To Your Bank Account $bank | $acc_holder_name | $acc_no" ;
			$user_balance = $my_new_wallet;
			$user_type_of_transaction = $type_of_transaction ;

			$query_transactions_cash_wallet_user  = " INSERT INTO transactions
			(
			user_ref_code,
			type_of_transaction,
			in_transactions,
			out_transactions,
			balance,
			description,
			status,
			created_date
			)
			VALUES
			(
			'$ref_code',
			'$user_type_of_transaction',
			'$user_in_transactions',
			'$user_out_transactions',
			'$user_balance',
			'$user_description',
			'$user_status',
			'$created_date'
			)";
			$res_transactions_cash_wallet_user = $mysqli->query($query_transactions_cash_wallet_user);
			*/
   
   			if($resultWT )
   			{		  

			/********************** Email To user *************************************************/
			$email_user = $user_email;
			$name_user = $user_name;

			$to_user      = $email_user;
			$subject_user = "Hi " . $name_user . ",  Withdrawal USD$withdraw_amount has been successfully credited to your bank account.";
        
			$message_user = "
			<html>
			<head>
			<title>Hi " . $name_user . ",  Withdrawal USD$withdraw_amount has been successfully credited to your bank account.</title>
			</head>
			<body>
			<p>

			Hai ".$name_user.",<br><br>

			The withdrawal detail as below:<br><br>

			Amount : ".$withdraw_amount."<br>
			Bank : ".$bank."<br>
			Account No : ".$acc_no."<br>

			</p>

			</body>
			</html>
			";       
			// Always set content-type when sending HTML email
			$headers_user = "MIME-Version: 1.0" . "\r\n";
			$headers_user .= 'Content-type:text/html;charset=UTF-8' . "\r\n";        
			// More headers
			$headers_user .= 'From: <finance@mygoldsdnbhd.com >' . "\r\n";
			$headers_user .= "Reply-To: finance@mygoldsdnbhd.com \r\n";
			$headers_user .= "Return-Path: finance@mygoldsdnbhd.com \r\n";
			mail($to_user, $subject_user, $message_user, $headers_user);
			/********************** Email To user *************************************************/

			/********************** Email To SuperAdmin *************************************************/
			$email_superadmin = 'syukranarpan@gmail.com';
			$name_superadmin = 'HQ';

			$to_superadmin      = $email_superadmin;
			$subject_superadmin = "Hi " . $name_superadmin . ", Withdrawal USD$withdraw_amount has been successfully credited to $user_name |  $user_email";
        
			$message_superadmin = "
			<html>
			<head>
			<title>Hi " . $name_superadmin . ", Withdrawal USD$withdraw_amount has been successfully credited to $user_name |  $user_email</title>
			</head>
			<body>
			<p>

			Hai ".$name_superadmin.",<br><br>

			The withdrawal detail as below:<br><br>

			Amount : ".$withdraw_amount."<br>
			Bank : ".$bank."<br>
			Account No : ".$acc_no."<br>
	
			</p>

			</body>
			</html>
			";       
			// Always set content-type when sending HTML email
			$headers_superadmin = "MIME-Version: 1.0" . "\r\n";
			$headers_superadmin .= 'Content-type:text/html;charset=UTF-8' . "\r\n";        
			// More headers
			$headers_superadmin .= 'From: <finance@mygoldsdnbhd.com >' . "\r\n";
			$headers_superadmin .= "Reply-To: finance@mygoldsdnbhd.com \r\n";
			$headers_superadmin .= "Return-Path: finance@mygoldsdnbhd.com \r\n";
			mail($to_superadmin, $subject_superadmin, $message_superadmin, $headers_superadmin);
			/********************** Email To SuperAdmin *************************************************/
		}
   }
		echo "<script type='text/javascript'>alert('Succesfully Withdraw To User');</script>";
		echo "<script type='text/javascript'>document.location='../U/wallet_history_bulk.php?type_wallet=$type_wallet'; </script>";	  
   	}
   	else 	  
   	{		  
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_history_bulk.php?type_wallet=$type_wallet'; </script>";	   
    }
}
?>


<?php
if (isset($_POST['Capital_Withdraw'])) 
{
   $purchase_code = $_POST['purchase_code'];
   $ref_code = $_POST['ref_code'];
   $PCK_id = $_POST['PCK_id'];
   $password = $_POST['password'];
   $package_price = $_POST['amount_to_withdraw'];

   date_default_timezone_set("Asia/Kuala_Lumpur");
   $created_date = date('Y-m-d');
   $today = date('Y-m-d');

   $sql_user = "SELECT *
             FROM user
             Where ref_code = '$ref_code'";
   $result_user = $mysqli-> query($sql_user);
   if ($result_user -> num_rows > 0)
   {
	  $row_user = $result_user ->fetch_assoc();
	  $My_password = $row_user['password'];
   }

   if ($My_password != $password)
   {
        echo "<script type='text/javascript'>alert('Please input correct password to proceed.');</script>";
		echo "<script type='text/javascript'>document.location='../U/list_of_package.php'; </script>";	
		exit();
   }

    $mysqli->begin_transaction();

   	//Get Package Info
	$sql_package_info = "SELECT * 
	FROM package_sale
	WHERE purchase_code='$purchase_code' 
	LIMIT 1";
	$result_package_info = $mysqli-> query($sql_package_info);
	if ($result_package_info -> num_rows > 0)
	{
		$row_package_info = $result_package_info ->fetch_assoc();
		$package_current_price = $row_package_info['package_price'];
		$package_purchase_date = $row_package_info['created_date'];
	}

	$date_1_year = date("Y-m-d", strtotime(date("Y-m-d", strtotime($package_purchase_date)) . " + 365 day"));

	if ($today < $date_1_year)
    {
       $fees_percent = 10 ;
	}
	else
	if ($today > $date_1_year)
	{
	    $fees_percent = 0 ;
	}

	$trans_code = randomRefferalCode();

	/**************************************************************** Member Transaction Start**********************************/
	//Get User Wallet Info
	$sql_my_wallet = "SELECT * FROM wallet
	WHERE ref_code='$ref_code' LIMIT 1";
	$result_my_wallet = $mysqli-> query($sql_my_wallet);
	if ($result_my_wallet -> num_rows > 0)
	{
		$row_my_wallet = $result_my_wallet ->fetch_assoc();
		$my_cash_wallet = $row_my_wallet['cash_wallet'];
		$my_pins_wallet = $row_my_wallet['pins_wallet'];
	}

	$fees_charge = ($fees_percent/100) * $package_price;

	$package_price_after_fees = $package_price - $fees_charge;

	$package_balance_price = $package_current_price - $package_price ;

    if ($package_balance_price < '0')
    {
        echo "<script type='text/javascript'>alert('Fail. Amount exceed package price');</script>";
		echo "<script type='text/javascript'>document.location='../U/list_of_package.php'; </script>";	
		exit();
    }

	$my_new_wallet = $my_pins_wallet + $package_price_after_fees;

	$Update_my_wallet = "UPDATE wallet SET   
	pins_wallet ='$my_new_wallet'
	WHERE ref_code ='$ref_code'";
	$resUpdate_my_wallet = $mysqli->query($Update_my_wallet);

	$status = '1';
	$in_transactions = $package_price_after_fees;
	$out_transactions = 0 ;
	$description = "Withdraw Investment Capital For PCK$PCK_id | $$package_price with fees $$fees_charge" ;
	$balance = $my_new_wallet;	
	$type_of_transaction = 'CW' ;
	$type_of_process = "Member Withdraw Investment Capital";

	$query_withdraw_transaction  = " INSERT INTO transactions
	(
	trans_code,
	type_of_process,
	user_ref_code,
	type_of_transaction,
	in_transactions,
	out_transactions,
	balance,
	fees,
	description,
	status,
	created_date
	)
	VALUES
	(
	'$trans_code',
	'$type_of_process',
	'$ref_code',
	'$type_of_transaction',
	'$in_transactions',
	'$out_transactions',
	'$balance',
	'$fees',
	'$description',
	'1',
	'$created_date'
	)";		
	$res_withdraw_transaction = $mysqli->query($query_withdraw_transaction);

	/**************************************************************** Member Transaction End**********************************/


	/**************************************************************** HQ Transaction Start**********************************/
	if ($fees_charge > 0)
	{
		//Get HQ Wallet Info
		$hq_ref_code = "MGP10000";

		$sql_hq_wallet = "SELECT * FROM wallet
		WHERE ref_code='$hq_ref_code' LIMIT 1";
		$result_hq_wallet = $mysqli-> query($sql_hq_wallet);
		if ($result_hq_wallet -> num_rows > 0)
		{
			$row_hq_wallet = $result_hq_wallet ->fetch_assoc();
			$hq_cash_wallet = $row_hq_wallet['cash_wallet'];
		}

		$hq_new_wallet = $hq_cash_wallet + $fees_charge;

		$Update_hq_wallet = "UPDATE wallet SET   
		cash_wallet ='$hq_new_wallet'
		WHERE ref_code ='$hq_ref_code'";
		$resUpdate_hq_wallet = $mysqli->query($Update_hq_wallet);

		$hq_status = '1';
		$hq_in_transactions = $fees_charge;
		$hq_out_transactions = 0 ;
		$hq_description = "Withdraw Fees Investment Capital $$fees_charge For PCK$PCK_id" ;
		$hq_balance = $hq_new_wallet;
		$hq_type_of_transaction = 'CW' ;
		$type_of_process_hq = "HQ Withdraw Fees Investment Capital";

		$query_fees_transaction  = " INSERT INTO transactions
		(
		trans_code,
		type_of_process,
		user_ref_code,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
		)
		VALUES
		(
		'$trans_code',
		'$type_of_process_hq',
		'$hq_ref_code',
		'$hq_type_of_transaction',
		'$hq_in_transactions',
		'$hq_out_transactions',
		'$hq_balance',
		'$hq_description',
		'1',
		'$created_date'
		)";		
		$res_fees_transaction = $mysqli->query($query_fees_transaction);
	}
	/**************************************************************** HQ Transaction End**********************************/
	//If withdraw all then set package unactive
	if ($package_balance_price == '0')
    {
        $Update_package_status= "UPDATE package_sale SET  
   		withdraw_status='1',
		package_price = '$package_balance_price'
   		WHERE purchase_code='$purchase_code' ";               
    }
	else
	{
	    $Update_package_status= "UPDATE package_sale SET  
		package_price = '$package_balance_price'
   		WHERE purchase_code='$purchase_code' ";            
	}
	
   	$result_package_status = $mysqli->query($Update_package_status);
	
   	if($resUpdate_my_wallet && $res_withdraw_transaction && $result_package_status)
   	{		  
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Succesfully Withdraw Investment Capital');</script>";
		echo "<script type='text/javascript'>document.location='../U/list_of_package.php'; </script>";	  
   	}
   	else 	  
   	{		  
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_package.php'; </script>";	   
    }
}
?>

<?php
if (isset($_POST['Update_System_Setting'])) 
{	
	$id = $_POST['id'];
	$withdraw_button = $_POST['withdraw_button'];
	$withdraw_profit_button = $_POST['withdraw_profit_button'];
	$tac_enablation_button = $_POST['tac_enablation_button'];
	$purchase_package_status = $_POST['purchase_package_status'];
	$login_status = $_POST['login_status'];
	$e_wallet_transfer = $_POST['e_wallet_transfer'];
	$a_wallet_transfer = $_POST['a_wallet_transfer'];
	$registration_payment_status = $_POST['registration_payment_status'] ?? "";

	if ($withdraw_button == "")
	{
		$withdraw_button = '0';
	}

	if ($withdraw_profit_button == "")
	{
		$withdraw_profit_button = '0';
	}

	if ($tac_enablation_button == "")
	{
		$tac_enablation_button = '0';
	}

	if ($purchase_package_status == "")
	{
		$purchase_package_status = '0';
	}

	if ($login_status == "")
	{
		$login_status = '0';
	}

	if ($e_wallet_transfer == "")
	{
		$e_wallet_transfer = '0';
	}

	if ($a_wallet_transfer == "")
	{
		$a_wallet_transfer = '0';
	}

	if ($registration_payment_status == "")
	{
		$registration_payment_status = '0';
	}
	
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE system_setting SET  
	withdraw_button ='$withdraw_button',
	withdraw_profit_button ='$withdraw_profit_button',
	tac_enablation_button ='$tac_enablation_button',
	purchase_package_status ='$purchase_package_status',
	login_status ='$login_status',
	e_wallet_transfer ='$e_wallet_transfer',
	a_wallet_transfer ='$a_wallet_transfer',
	registration_payment_status ='$registration_payment_status'
	WHERE id='$id' ";               
	$result_setting = $mysqli->query($UpdateQuery);

	if($result_setting)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update Setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
	}
}
?>

<?php
if (isset($_POST['Update_Withdraw_Fees']))
{
    $id = $_POST['id'];
    $withdraw_fees = $_POST['withdraw_fees'];

    if ($withdraw_fees === '' || $withdraw_fees === null) {
        $withdraw_fees = '0';
    }

    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE system_setting SET
                    withdraw_fees = '$withdraw_fees'
                    WHERE id = '$id'";
    $result_setting = $mysqli->query($UpdateQuery);

    if ($result_setting)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Update Withdraw Fees');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
}
?>

<?php
if (isset($_POST['Update_Registration_Fee']))
{
    $id = $_POST['id'];
    $registration_fee = $_POST['registration_fee'];

    if ($registration_fee === '' || $registration_fee === null) {
        $registration_fee = '0';
    }

    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE system_setting SET
                    registration_fee = '$registration_fee'
                    WHERE id = '$id'";
    $result_setting = $mysqli->query($UpdateQuery);

    if ($result_setting)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Update Registration Fee');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
}
?>

<?php
if (isset($_POST['Update_Bonus_Sponsor']))
{
    $id = $_POST['id'];
    $bonus_sponsor = $_POST['bonus_sponsor'];

    if ($bonus_sponsor === '' || $bonus_sponsor === null) {
        $bonus_sponsor = '0';
    }

    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE system_setting SET
                    bonus_sponsor = '$bonus_sponsor'
                    WHERE id = '$id'";
    $result_setting = $mysqli->query($UpdateQuery);

    if ($result_setting)
    {
        $mysqli->commit();
        echo "<script type='text/javascript'>alert('Successfully Update Bonus Sponsor');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
    else
    {
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
        echo "<script type='text/javascript'> document.location='../U/system_setting.php'; </script>";
    }
}
?>

<?php
if (isset($_POST['Action_List_Of_Comission_Setting'])) 
{
	$id = $_POST['id'];

	$Type_Of_Comm = $_POST['Type_Of_Comm'];

	if ( $Type_Of_Comm == 'Registration Commission')
	{
	     $page = "comission_setting.php";
	}
	else
	if ( $Type_Of_Comm == 'Item Commission')
	{
	     $page = "item_comission_setting_1.php";
	}
	
	$Package_Name = $_POST['Package_Name'];
	$Item_Name = $_POST['Item_Name'];
	$Price = $_POST['Price'];
	$Valid_Month = $_POST['Valid_Month'];
	$Penaja = $_POST['Penaja'];
	$Bonus_Peribadi = $_POST['Bonus_Peribadi'];
	$Stokist = $_POST['Stokist'];
	$Keyin = $_POST['Keyin'];

	$Level_1 = $_POST['Level_1'];
	$Level_2 = $_POST['Level_2'];
	$Level_3 = $_POST['Level_3'];
	$Level_4 = $_POST['Level_4'];
	$Level_5 = $_POST['Level_5'];
	$Level_6 = $_POST['Level_6'];
	$Level_7 = $_POST['Level_7'];
	$Level_8 = $_POST['Level_8'];
	$Level_9 = $_POST['Level_9'];
	$Level_10 = $_POST['Level_10'];

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE comission_setting SET  
	Package_Name='$Package_Name', 
	Item_Name='$Item_Name', 
	Price='$Price', 
	Valid_Month='$Valid_Month', 
	Bonus_Peribadi='$Bonus_Peribadi', 
	Penaja='$Penaja', 
	Stokist='$Stokist', 
	Keyin='$Keyin', 
	Level_1='$Level_1', 
	Level_2='$Level_2', 
	Level_3='$Level_3', 
	Level_4='$Level_4',
	Level_5='$Level_5',
	Level_6='$Level_6',
	Level_7='$Level_7',
	Level_8='$Level_8',
	Level_9='$Level_9',
	Level_10='$Level_10' 
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page'; </script>";	 
	}
	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/$page'; </script>";	  
	}     
}
?>

<?php
if (isset($_GET['form_name_Delete_comission_setting'])=='Delete_comission_setting') 
{
	$id = $_GET['id'];
	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE comission_setting SET  
	status='9'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Delete comission setting');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_comission_setting_1.php'; </script>";
	}
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/item_comission_setting_1.php'; </script>";
	}        
}
?>

<?php
session_start();

if (isset($_POST['topup_wallet'])) 
{
	$amount = $_POST['amount'];
	$payment_type = $_POST['payment_type'];

	$name = $_POST['name'];
	$email = $_POST['email'];
	$user_ref_code = $_POST['user_ref_code'];

	$reference1 = $_POST['reference'];
	$reference  = htmlspecialchars($reference1, ENT_QUOTES);

	$ref_code = $_POST['ref_code'];

	$sql_check_user = "SELECT * FROM user 
	WHERE ref_code='$ref_code' 
	And status='1'
	LIMIT 1";
	$result_check_user = $mysqli-> query($sql_check_user);
	if ($result_check_user -> num_rows > 0)
	{
		$row_check_user = $result_check_user ->fetch_assoc();
		$check_ref_code = $row_check_user['ref_code'];
		$check_email = $row_check_user['email'];
	}

	$at_page = 'topup_wallet' ;

	if ( $check_ref_code != $user_ref_code || $check_email != $email)
	{
		//echo "<script type='text/javascript'>alert('Fail.Your Email/User ID not matching. Please try again');</script>";
		echo "<script type='text/javascript'> document.location='../User/topup_wallet.php?status_code=NM&at_page=".$at_page." '; </script>";
		exit();
	}

	if ( $payment_type == 'OB')
	{
		$action = htmlentities($_SERVER['PHP_SELF']); 

		$_SESSION['amount_Sale'] = $amount ;
		$_SESSION['name_Sale'] = $name ;
		$_SESSION['payment_type_Sale'] = $payment_type ;
		$_SESSION['email_Sale'] = $email ;
		$_SESSION['user_ref_code_Sale'] = $user_ref_code ;
		$_SESSION['ref_code_Sale'] = $ref_code ;

		echo "<script type='text/javascript'> document.location='../User/checkout_proceed_B_payment.php '; </script>";
		exit();		
	}
       
	$topup_code = randomRefferalCode();
        
	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$created_by = $_POST['user_id'];
        
	$mysqli->begin_transaction();

	$target_dir = "uploads/";
	$temp1 = $temp1 = explode(".", $_FILES["fileToUpload1"]["name"]);
	$newfilename1 = $topup_code . '1.' . end($temp1);
	$target_file1 = $target_dir . basename($newfilename1);
	$uploadOk = 1;
	$imageFileType1 = pathinfo($target_file1,PATHINFO_EXTENSION);

	// Check if image file is a actual image or fake image
	if(isset($_POST["submit"]))
	{
		$check1 = getimagesize($_FILES["fileToUpload1"]["tmp_name"]);
		if( ($check1 !== false) )
		{
		echo "File is an Image - " . $check1["mime"] . ".";
		$uploadOk = 1;
		} else 
		{
		echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
		$uploadOk = 0;
		}
	}

	// Check if file already exists
	if ( (file_exists($target_file1)) )
	{
		echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
		$uploadOk = 0;
	}

	// Allow certain file formats
	if($imageFileType1 != "png" && $imageFileType1 != "PNG" &&
	$imageFileType1 != "jpg" && $imageFileType1 != "JPG" &&
	$imageFileType1 != "pdf" && $imageFileType1 != "PDF" )
	{
		echo "<script type='text/javascript'>alert('Sorry, only PNG,JPG and PDF files are allowed.');</script>";
		$uploadOk = 0;
	}

	// Check if $uploadOk is set to 0 by an error
	if ($uploadOk == 0)
	{
		echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
		// if everything is ok, try to upload file
	}
	else
	{
		if ( move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"], $target_file1)  )
		{
		//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
		//echo "<script type='text/javascript'>alert('The file has been uploaded.');</script>";
		$attachment_image = $topup_code . '1.' . end($temp1);

		//Insert Into topup_wallet

			if ( $payment_type == 'BC') //Payment Using Blockchain
			{   
				$status = 'SBC';
				$coloumn_name = 'BC_transaction_image' ;
				$success_status_code = 'STBC';
				$fail_status_code = 'FTBC';
			}
			else
			if ( $payment_type == 'TCA') //Payment Using TRansfer To Comp Acc
			{
				$status = 'STCA';
				$coloumn_name = 'attachment_image' ;
				$success_status_code = 'STCA';
				$fail_status_code = 'STCA';
			}

			$query_topup  = " INSERT INTO topup_wallet
			(
			topup_code,
			ref_code,
			$coloumn_name,
			payment_type,
			amount,
			reference,
			status,
			created_date,
			created_by
			)
			VALUES
			(
			'$topup_code',
			'$ref_code',
			'$attachment_image',
			'$payment_type',
			'$amount',
			'$reference',	
			'$status',
			'$created_date',
			'$created_by'
			)";
			$res_topup = $mysqli->query($query_topup);
			}
			else
			{
				echo "<script type='text/javascript'>alert('Sorry, there was an error uploading your file.');</script>";
				echo "<script type='text/javascript'> document.location='../User/topup_wallet.php?status_code=EU&at_page=".$at_page." '; </script>";
				exit();
			}
		}
				
		if ($res_topup) 
		{
			$mysqli->commit();   
			//echo "<script type='text/javascript'>alert('Terima Kasih . Sila lihat inbox email anda');</script>";
			echo "<script type='text/javascript'> document.location='../User/topup_wallet.php?status_code=".$success_status_code."&at_page=".$at_page." '; </script>";
			exit();
		} 
		else 
		{
			$mysqli->rollback();
			//echo "<script type='text/javascript'>alert('Gagal');</script>";
			echo "<script type='text/javascript'> document.location='../User/topup_wallet.php?status_code=".$fail_status_code."'; </script>";
			exit();
		}
}

?>

<?php
if (isset($_POST['admin_update_personal_detail'])) {
    
	$at_page = 'settings';
    $user_id = $_POST['user_id'];
    
    $name1 = $_POST['name'];
    $name  = htmlspecialchars($name1, ENT_QUOTES);
    
    $phone_number = $_POST['phone_number'];
        
    $password1 = $_POST['password'];
    $password  = htmlspecialchars($password1, ENT_QUOTES);
    
	$no_ic = $_POST['no_ic'];
	
	$address1 = $_POST['address'];
    $address  = htmlspecialchars($address1, ENT_QUOTES);
    
    date_default_timezone_set("Asia/Kuala_Lumpur");
    $updated_date = date('Y-m-d H:i:s');
    
    $mysqli->begin_transaction();

    $UpdateQuery = "UPDATE user SET  
	name='$name',
	phone_number='$phone_number',
	password='$password',
	no_ic='$no_ic',
	address='$address',
	updated_date='$updated_date',
	updated_by='$user_id'
	WHERE id='$user_id' ";
    $result = $mysqli->query($UpdateQuery);
    
    if ($result) 
	{
        $mysqli->commit();
		//echo "<script type='text/javascript'>alert('Successfully updated your personal details');</script>";
        echo "<script type='text/javascript'> document.location='../Admin/settings.php?status_code=1&at_page=".$at_page." '; </script>";
		exit();
    }  
    else 
	{
        $mysqli->rollback();
		//echo "<script type='text/javascript'>alert('Fail. Please try again');</script>";
        echo "<script type='text/javascript'> document.location='../Admin/settings.php?status_code=0&at_page=".$at_page." '; </script>";
		exit();
    }   
}
?>

<?php
if (isset($_POST['add_new_admin']))
{
	$level = $_POST['level'];
	
	$name1 = $_POST['name'];
	$name  = htmlspecialchars($name1, ENT_QUOTES);

	$no_ic = $_POST['no_ic'];

    $email1 = $_POST['email'];
    $email  = htmlspecialchars($email1, ENT_QUOTES);

	$password1 = $_POST['password'];
    $password  = htmlspecialchars($password1, ENT_QUOTES);
		
	$password_retype1 = $_POST['password_retype'];
	$password_retype  = htmlspecialchars($password_retype1, ENT_QUOTES);

	$remark1 = $_POST['remark'];
    $remark  = htmlspecialchars($remark1, ENT_QUOTES);

	if ( $password != $password_retype) 
	{
        echo "<script type='text/javascript'>alert('Error.Please make sure Password and Retype Password is same');</script>";
		echo "<script type='text/javascript'> document.location='../Admin/list_of_admin.php'; </script>";
		exit();
	}
	
	$phone_number = $_POST['phone_number'];
	
    $sponsor_code1 = $_POST['ref_code'];
    $sponsor_code  = htmlspecialchars($sponsor_code1, ENT_QUOTES);

    $sponsor_coloumn_name = 'sponsor_code';
			    
    $sql = "SELECT * FROM user 
	WHERE email='$email' 
	And status='1'
	LIMIT 1";
	$result = $mysqli-> query($sql);
	if ($result -> num_rows > 0)
	{
		$row = $result ->fetch_assoc();
		echo "<script type='text/javascript'>alert('Fail.This email already exist in our system');</script>";
		echo "<script type='text/javascript'> document.location='../Admin/list_of_admin.php'; </script>";
		exit();
	}
	              		              
    $sentence = substr($email,0,6);
    $random_number =(rand(10,10000));
    $stripped = preg_replace('/\s/', '', $sentence);
    $user_ref_code = $stripped . $random_number;
        
    $status = '1';
    //$level  = '1';
        
    date_default_timezone_set("Asia/Kuala_Lumpur");
    $created_date = date('Y-m-d H:i:s');
        
	$mysqli->begin_transaction();
         
    $query_user  = " INSERT INTO user
	(
	level,
	ref_code,
	$sponsor_coloumn_name, 
	email,
	password,
	no_ic,
	name,
	phone_number,
	remark,
	status,
	created_date
	)
	VALUES
	(
	'$level',
	'$user_ref_code',
	'$sponsor_code',
	'$email',
	'$password',
	'$no_ic',
	'$name',
	'$phone_number',
	'$remark',
	'$status',
	'$created_date'
	)";
    $res_package = $mysqli->query($query_user);

	$query_wallet  = " INSERT INTO wallet
	(
	ref_code,	
	created_date
	)
	VALUES
	(
	'$user_ref_code',	
	'$created_date'
	)";
    $res_wallet = $mysqli->query($query_wallet);
		
		       
    $sql = "SELECT  id 
	FROM user 
	Where ref_code='$sponsor_code' 
	LIMIT 1";
	$result = $mysqli-> query($sql);
	if ($result -> num_rows > 0)
	{
		$row = $result ->fetch_assoc();
		$id         = $row['id'];
	}

    $created_by = $id;
        
    $UpdateQuery1 = "UPDATE user SET   
	created_by ='$created_by' 
	WHERE ref_code ='$user_ref_code'";
    $resUpdatePackage = $mysqli->query($UpdateQuery1);

    
    if ( $res_package && $res_wallet && $resUpdatePackage ) {
        $mysqli->commit();
        
        $to      = $email;
        $subject = "Hi " . $name . ", mygoldsdnbhd.com Registration";
        
        $message = "
		<html>
		<head>
		<title>Hi '" . $name . "', mygoldsdnbhd.com Registration</title>
		</head>
		<body>
		<p>

		Hai " . $name . ",<br><br>

		Admin Registered You As Admin In mygoldsdnbhd.com System <br><br>

		This Is Your Credential Info :<br>
		Link : https://mygoldsdnbhd.com/Form/Login.php <br>
		Name : ".$name." <br>
		Username : ".$email." <br>
		Password : ".$password." <br><br>
		</p>

		</body>
		</html>
		";
        
        // Always set content-type when sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= 'Content-type:text/html;charset=UTF-8' . "\r\n";
        // More headers
		$headers .= 'From: <syukranarpan@gmail.com >' . "\r\n";
		$headers .= "Reply-To: syukranarpan@gmail.com \r\n";
		$headers .= "Return-Path: mygoldplt_websystemmambrurgmail.com \r\n";
		$headers .= "CC: syukranarpan@gmail.com \r\n";
		$headers .= "BCC: syukranarpan@gmail.com \r\n";
		mail($to, $subject, $message, $headers);

        echo "<script type='text/javascript'>alert('Succesfully Register New Admin');</script>";
        echo "<script type='text/javascript'> document.location='../Admin/list_of_admin.php'; </script>";
		exit();
        
    } else 
	{
        $mysqli->rollback();
        echo "<script type='text/javascript'>alert('Fail');</script>";
        echo "<script type='text/javascript'> document.location='../Admin/list_of_admin.php'; </script>";
		exit();
    }
}

?>


<?php
function sum_of_package($ref_code)
{
	global $mysqli;
	
	$data_total_sum =
    "select SUM(package_price) As num 
    from package_sale
    Where ref_code ='$ref_code'
	And status='1' ";    
	$result_total_sum = $mysqli-> query($data_total_sum);
	if ($result_total_sum -> num_rows > 0)
	{
		$row_total_sum = $result_total_sum ->fetch_assoc();
		$total_sum = number_format($row_total_sum['num'],2);  
	}

	if ($total_sum >= 200)
	{	
		$Update_user_type = "UPDATE user SET  
		type_of_user='Stokist'
		WHERE ref_code='$ref_code' ";
		$result_Update_user_type = $mysqli->query($Update_user_type);
	}
}
?>

<?php
if (isset($_POST['Update_Wallet_Balance'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$cash_wallet = htmlspecialchars($_POST['cash_wallet'], ENT_QUOTES);
	$product_wallet = htmlspecialchars($_POST['product_wallet'], ENT_QUOTES);
	$pins_wallet = htmlspecialchars($_POST['pins_wallet'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE wallet SET  
	cash_wallet='$cash_wallet'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_setting_1.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_setting_1.php'; </script>";	  
	}     
}
?>


<?php
if (isset($_POST['Update_wallet_history_balance'])) 
{
	$id = htmlspecialchars($_POST['id'], ENT_QUOTES);
	$balance = htmlspecialchars($_POST['balance'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE withdraw_transaction SET  
	balance='$balance'
	WHERE id='$id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_history.php'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/wallet_history.php'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['update_transaction'])) 
{
	$comm_id = htmlspecialchars($_POST['comm_id'], ENT_QUOTES);
	$in_transactions = htmlspecialchars($_POST['in_transactions'], ENT_QUOTES);
	$balance = htmlspecialchars($_POST['balance'], ENT_QUOTES);
	$created_date = htmlspecialchars($_POST['created_date'], ENT_QUOTES);

   	$mysqli->begin_transaction();

	$UpdateQuery= "UPDATE transactions SET  
	in_transactions='$in_transactions',
	balance='$balance',
	created_date='$created_date'
	WHERE id='$comm_id' ";               
	$result = $mysqli->query($UpdateQuery);
	   
	if($result)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Update');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_commission_update.php?comm_id=$comm_id'; </script>";	 
	}	   
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/list_of_commission_update.php?comm_id=$comm_id'; </script>";	  
	}     
}
?>

<?php
if (isset($_POST['Update_Umrah_Date'])) 
{
    $order_info_id = $_POST['order_info_id'];
    $umrah_date = $_POST['umrah_date'];

    // basic validation
    if ($order_info_id == '' || $umrah_date == '') {
        echo "<script>alert('Invalid input');</script>";
        echo "<script>history.back();</script>";
        exit();
    }

    $order_info_id = $mysqli->real_escape_string($order_info_id);
    $umrah_date = $mysqli->real_escape_string($umrah_date);

    $mysqli->begin_transaction();

    $q = "UPDATE woocommerce_order_info
          SET umrah_date = '$umrah_date'
          WHERE id = '$order_info_id'";
    $res = $mysqli->query($q);

    if ($res) 
	{
		$mysqli->commit();

		$back = $_SERVER['HTTP_REFERER'] ?? '../U/list_of_package.php';
		// Prevent header injection
		$back = str_replace(["\r", "\n"], '', $back);

		echo "<script>alert('Umrah Date updated successfully');</script>";
		echo "<script>window.location.href = '$back';</script>";
		exit();
	} else {
		$mysqli->rollback();

		$back = $_SERVER['HTTP_REFERER'] ?? '../U/list_of_package.php';
		$back = str_replace(["\r", "\n"], '', $back);

		echo "<script>alert('Failed to update Umrah Date');</script>";
		echo "<script>window.location.href = '$back';</script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['Add_Upah_Simpan_Gold']))
{
	$user_ref_code = $_SESSION['ref_code'];
	$upah_simpan_gold_ref_code = randomRefferalCode();

	$emas_ref_code = $mysqli->real_escape_string(htmlspecialchars($_POST['emas_ref_code'], ENT_QUOTES));
	$item_code = $mysqli->real_escape_string(htmlspecialchars($_POST['item_code'], ENT_QUOTES));
	$gold_weight = (float)$_POST['gold_weight'];
	$customer_full_name = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_full_name'], ENT_QUOTES));
	$customer_email = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_email'], ENT_QUOTES));
	$customer_phone_number = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_phone_number'], ENT_QUOTES));
	$customer_address = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_address'], ENT_QUOTES));
	$upah_simpan_remark = $mysqli->real_escape_string(htmlspecialchars($_POST['upah_simpan_remark'], ENT_QUOTES));

	if ($user_ref_code == "" || $emas_ref_code == "" || $item_code == "" || $gold_weight <= 0)
	{
		echo "<script type='text/javascript'>alert('Invalid upah simpan gold information.');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
		exit();
	}

	$sql_item_code = "SELECT id
					  FROM upah_simpan_gold
					  WHERE item_code='$item_code'
					    AND status='1'
					  LIMIT 1";
	$result_item_code = $mysqli->query($sql_item_code);
	if ($result_item_code && $result_item_code->num_rows > 0)
	{
		echo "<script type='text/javascript'>alert('Item Code already exists. Please key in another Item Code.');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
		exit();
	}

	$sql_emas = "SELECT *
				 FROM emas_setting
				 WHERE emas_ref_code='$emas_ref_code'
				   AND status='1'
				 LIMIT 1";
	$result_emas = $mysqli->query($sql_emas);
	if (!$result_emas || $result_emas->num_rows == 0)
	{
		echo "<script type='text/javascript'>alert('Selected gold setting not found.');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
		exit();
	}

	$row_emas = $result_emas->fetch_assoc();
	$emas_name = $mysqli->real_escape_string(htmlspecialchars($row_emas['emas_name'], ENT_QUOTES));
	$emas_price = (float)$row_emas['emas_price'];
	$emas_upah_simpan = (float)$row_emas['emas_upah_simpan'];
	$total_price = (float)number_format($emas_price * $gold_weight, 2, '.', '');
	$upah_simpan_amount = (float)number_format(($total_price * $emas_upah_simpan) / 100, 2, '.', '');

	$attachment_files = array();
	if (isset($_FILES['upah_simpan_gold_attachments']) && is_array($_FILES['upah_simpan_gold_attachments']['name']))
	{
		for ($i = 0; $i < count($_FILES['upah_simpan_gold_attachments']['name']); $i++)
		{
			if ($_FILES['upah_simpan_gold_attachments']['name'][$i] != "")
			{
				$attachment_files[] = $i;
			}
		}
	}

	if (count($attachment_files) > 3)
	{
		echo "<script type='text/javascript'>alert('Maximum 3 attachments only.');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
		exit();
	}

	$allowed_extensions = array("pdf", "jpg", "jpeg", "png", "gif", "webp");
	$max_file_size = 10 * 1024 * 1024;
	$uploaded_attachments = array("", "", "");
	$attachment_position = 0;
	$target_dir = "../Controller/uploads/";

	foreach ($attachment_files as $file_index)
	{
		if ($_FILES['upah_simpan_gold_attachments']['size'][$file_index] > $max_file_size)
		{
			echo "<script type='text/javascript'>alert('Each attachment must be below 10MB.');</script>";
			echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
			exit();
		}

		$original_name = $_FILES['upah_simpan_gold_attachments']['name'][$file_index];
		$file_extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
		if (!in_array($file_extension, $allowed_extensions))
		{
			echo "<script type='text/javascript'>alert('Only PDF or image attachments are allowed.');</script>";
			echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
			exit();
		}

		$new_attachment_name = $upah_simpan_gold_ref_code . "_" . ($attachment_position + 1) . "_" . time() . "." . $file_extension;
		$target_file = $target_dir . basename($new_attachment_name);

		if (!move_uploaded_file($_FILES['upah_simpan_gold_attachments']['tmp_name'][$file_index], $target_file))
		{
			echo "<script type='text/javascript'>alert('Failed to upload attachment.');</script>";
			echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
			exit();
		}

		$uploaded_attachments[$attachment_position] = $new_attachment_name;
		$attachment_position++;
	}

	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$status = 1;

	$mysqli->begin_transaction();

	$query_upah_simpan_gold = "INSERT INTO upah_simpan_gold
	(
		upah_simpan_gold_ref_code,
		user_ref_code,
		emas_ref_code,
		emas_name,
		emas_price,
		emas_upah_simpan,
		item_code,
		gold_weight,
		total_price,
		upah_simpan_amount,
		customer_full_name,
		customer_email,
		customer_phone_number,
		customer_address,
		upah_simpan_remark,
		attachment_1,
		attachment_2,
		attachment_3,
		status,
		created_date
	)
	VALUES
	(
		'$upah_simpan_gold_ref_code',
		'$user_ref_code',
		'$emas_ref_code',
		'$emas_name',
		'$emas_price',
		'$emas_upah_simpan',
		'$item_code',
		'$gold_weight',
		'$total_price',
		'$upah_simpan_amount',
		'$customer_full_name',
		'$customer_email',
		'$customer_phone_number',
		'$customer_address',
		'$upah_simpan_remark',
		'$uploaded_attachments[0]',
		'$uploaded_attachments[1]',
		'$uploaded_attachments[2]',
		'$status',
		'$created_date'
	)";
	$result_upah_simpan_gold = $mysqli->query($query_upah_simpan_gold);

	if ($result_upah_simpan_gold)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Submit Upah Simpan Gold');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_view.php'; </script>";
		exit();
	}
	else
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/upah_simpan_gold_add.php'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['Add_Gold_Buy_Back']))
{
	$user_ref_code = $_SESSION['ref_code'];
	$gold_buy_back_ref_code = randomRefferalCode();
	$trans_code = randomRefferalCode();

	$emas_ref_code = $mysqli->real_escape_string(htmlspecialchars($_POST['emas_ref_code'], ENT_QUOTES));
	$item_code = $mysqli->real_escape_string(htmlspecialchars($_POST['item_code'], ENT_QUOTES));
	$gold_weight = (float)$_POST['gold_weight'];
	$customer_full_name = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_full_name'], ENT_QUOTES));
	$customer_email = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_email'], ENT_QUOTES));
	$customer_phone_number = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_phone_number'], ENT_QUOTES));
	$customer_address = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_address'], ENT_QUOTES));
	$buy_back_remark = $mysqli->real_escape_string(htmlspecialchars($_POST['buy_back_remark'], ENT_QUOTES));

	if ($user_ref_code == "" || $emas_ref_code == "" || $item_code == "" || $gold_weight <= 0)
	{
		echo "<script type='text/javascript'>alert('Invalid gold buy back information.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}

	$sql_item_code = "SELECT id
					  FROM gold_buy_back
					  WHERE item_code='$item_code'
					    AND status='1'
					  LIMIT 1";
	$result_item_code = $mysqli->query($sql_item_code);
	if ($result_item_code && $result_item_code->num_rows > 0)
	{
		echo "<script type='text/javascript'>alert('Item Code already exists. Please key in another Item Code.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}

	$sql_emas = "SELECT *
				 FROM emas_setting
				 WHERE emas_ref_code='$emas_ref_code'
				   AND status='1'
				 LIMIT 1";
	$result_emas = $mysqli->query($sql_emas);
	if (!$result_emas || $result_emas->num_rows == 0)
	{
		echo "<script type='text/javascript'>alert('Selected gold setting not found.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}

	$row_emas = $result_emas->fetch_assoc();
	$emas_name = $mysqli->real_escape_string(htmlspecialchars($row_emas['emas_name'], ENT_QUOTES));
	$emas_price = (float)$row_emas['emas_price'];
	$emas_buy_back_percent = (float)$row_emas['emas_buy_back_percent'];
	$buy_back_total_price = (float)number_format($emas_price * $gold_weight, 2, '.', '');
	$commission_amount = (float)number_format(($buy_back_total_price * $emas_buy_back_percent) / 100, 2, '.', '');

	$attachment_files = array();
	if (isset($_FILES['gold_buy_back_attachments']) && is_array($_FILES['gold_buy_back_attachments']['name']))
	{
		for ($i = 0; $i < count($_FILES['gold_buy_back_attachments']['name']); $i++)
		{
			if ($_FILES['gold_buy_back_attachments']['name'][$i] != "")
			{
				$attachment_files[] = $i;
			}
		}
	}

	if (count($attachment_files) > 3)
	{
		echo "<script type='text/javascript'>alert('Maximum 3 attachments only.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}

	$allowed_extensions = array("pdf", "jpg", "jpeg", "png", "gif", "webp");
	$max_file_size = 10 * 1024 * 1024;
	$uploaded_attachments = array("", "", "");
	$attachment_position = 0;
	$target_dir = "../Controller/uploads/";

	foreach ($attachment_files as $file_index)
	{
		if ($_FILES['gold_buy_back_attachments']['size'][$file_index] > $max_file_size)
		{
			echo "<script type='text/javascript'>alert('Each attachment must be below 10MB.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
			exit();
		}

		$original_name = $_FILES['gold_buy_back_attachments']['name'][$file_index];
		$file_extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
		if (!in_array($file_extension, $allowed_extensions))
		{
			echo "<script type='text/javascript'>alert('Only PDF or image attachments are allowed.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
			exit();
		}

		$new_attachment_name = $gold_buy_back_ref_code . "_" . ($attachment_position + 1) . "_" . time() . "." . $file_extension;
		$target_file = $target_dir . basename($new_attachment_name);

		if (!move_uploaded_file($_FILES['gold_buy_back_attachments']['tmp_name'][$file_index], $target_file))
		{
			echo "<script type='text/javascript'>alert('Failed to upload attachment.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
			exit();
		}

		$uploaded_attachments[$attachment_position] = $new_attachment_name;
		$attachment_position++;
	}

	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$status = 1;

	$mysqli->begin_transaction();

	$sql_wallet = "SELECT cash_wallet
				   FROM wallet
				   WHERE ref_code='$user_ref_code'
				   LIMIT 1";
	$result_wallet = $mysqli->query($sql_wallet);
	if (!$result_wallet || $result_wallet->num_rows == 0)
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Wallet not found.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}

	$row_wallet = $result_wallet->fetch_assoc();
	$current_cash_wallet = (float)$row_wallet['cash_wallet'];
	$new_cash_wallet = (float)number_format($current_cash_wallet + $commission_amount, 2, '.', '');

	$query_gold_buy_back = "INSERT INTO gold_buy_back
	(
		gold_buy_back_ref_code,
		user_ref_code,
		emas_ref_code,
		emas_name,
		emas_price,
		emas_buy_back_percent,
		item_code,
		gold_weight,
		buy_back_total_price,
		customer_full_name,
		customer_email,
		customer_phone_number,
		customer_address,
		buy_back_remark,
		attachment_1,
		attachment_2,
		attachment_3,
		commission_amount,
		trans_code,
		status,
		created_date
	)
	VALUES
	(
		'$gold_buy_back_ref_code',
		'$user_ref_code',
		'$emas_ref_code',
		'$emas_name',
		'$emas_price',
		'$emas_buy_back_percent',
		'$item_code',
		'$gold_weight',
		'$buy_back_total_price',
		'$customer_full_name',
		'$customer_email',
		'$customer_phone_number',
		'$customer_address',
		'$buy_back_remark',
		'$uploaded_attachments[0]',
		'$uploaded_attachments[1]',
		'$uploaded_attachments[2]',
		'$commission_amount',
		'$trans_code',
		'$status',
		'$created_date'
	)";
	$result_gold_buy_back = $mysqli->query($query_gold_buy_back);

	$Update_wallet = "UPDATE wallet SET
	cash_wallet='$new_cash_wallet'
	WHERE ref_code='$user_ref_code'";
	$result_wallet_update = $mysqli->query($Update_wallet);

	$type_of_process = "Gold Buy Back Commission";
	$type_of_transaction = "CW";
	$in_transactions = $commission_amount;
	$out_transactions = 0;
	$description = $mysqli->real_escape_string("Gold Buy Back Commission | Buy Back ID: $gold_buy_back_ref_code | Gold: $emas_name | Item Code: $item_code | Weight: " . number_format($gold_weight, 2) . " gram | Total Price: RM " . number_format($buy_back_total_price, 2) . " | Buy Back Percent: " . number_format($emas_buy_back_percent, 2) . "% | Customer: $customer_full_name");

	$query_transactions = "INSERT INTO transactions
	(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
	)
	VALUES
	(
		'$user_ref_code',
		'$trans_code',
		'$type_of_process',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$new_cash_wallet',
		'$description',
		'$status',
		'$created_date'
	)";
	$result_transactions = $mysqli->query($query_transactions);

	if ($result_gold_buy_back && $result_wallet_update && $result_transactions)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Submit Gold Buy Back');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_view.php'; </script>";
		exit();
	}
	else
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_buy_back_add.php'; </script>";
		exit();
	}
}
?>

<?php
if (isset($_POST['Add_Gold_Sales']))
{
	$user_ref_code = $_SESSION['ref_code'];
	$gold_sale_ref_code = randomRefferalCode();
	$trans_code = randomRefferalCode();

	$emas_ref_code = $mysqli->real_escape_string(htmlspecialchars($_POST['emas_ref_code'], ENT_QUOTES));
	$item_code = $mysqli->real_escape_string(htmlspecialchars($_POST['item_code'], ENT_QUOTES));
	$gold_weight = (float)$_POST['gold_weight'];
	$customer_full_name = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_full_name'], ENT_QUOTES));
	$customer_email = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_email'], ENT_QUOTES));
	$customer_phone_number = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_phone_number'], ENT_QUOTES));
	$customer_address = $mysqli->real_escape_string(htmlspecialchars($_POST['customer_address'], ENT_QUOTES));
	$sale_remark = $mysqli->real_escape_string(htmlspecialchars($_POST['sale_remark'], ENT_QUOTES));

	if ($user_ref_code == "" || $emas_ref_code == "" || $item_code == "" || $gold_weight <= 0)
	{
		echo "<script type='text/javascript'>alert('Invalid gold sale information.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}

	$sql_item_code = "SELECT id
					  FROM gold_sales
					  WHERE item_code='$item_code'
					    AND status='1'
					  LIMIT 1";
	$result_item_code = $mysqli->query($sql_item_code);
	if ($result_item_code && $result_item_code->num_rows > 0)
	{
		echo "<script type='text/javascript'>alert('Item Code already exists. Please key in another Item Code.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}

	$sql_emas = "SELECT *
				 FROM emas_setting
				 WHERE emas_ref_code='$emas_ref_code'
				   AND status='1'
				 LIMIT 1";
	$result_emas = $mysqli->query($sql_emas);
	if (!$result_emas || $result_emas->num_rows == 0)
	{
		echo "<script type='text/javascript'>alert('Selected gold setting not found.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}

	$row_emas = $result_emas->fetch_assoc();
	$emas_name = $mysqli->real_escape_string(htmlspecialchars($row_emas['emas_name'], ENT_QUOTES));
	$emas_price = (float)$row_emas['emas_price'];
	$emas_sale_profit_pergram = (float)$row_emas['emas_sale_profit_pergram'];
	$commission_amount = (float)number_format($gold_weight * $emas_sale_profit_pergram, 2, '.', '');

	$attachment_files = array();
	if (isset($_FILES['gold_sale_attachments']) && is_array($_FILES['gold_sale_attachments']['name']))
	{
		for ($i = 0; $i < count($_FILES['gold_sale_attachments']['name']); $i++)
		{
			if ($_FILES['gold_sale_attachments']['name'][$i] != "")
			{
				$attachment_files[] = $i;
			}
		}
	}

	if (count($attachment_files) > 3)
	{
		echo "<script type='text/javascript'>alert('Maximum 3 attachments only.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}

	$allowed_extensions = array("pdf", "jpg", "jpeg", "png", "gif", "webp");
	$max_file_size = 10 * 1024 * 1024;
	$uploaded_attachments = array("", "", "");
	$attachment_position = 0;
	$target_dir = "../Controller/uploads/";

	foreach ($attachment_files as $file_index)
	{
		if ($_FILES['gold_sale_attachments']['size'][$file_index] > $max_file_size)
		{
			echo "<script type='text/javascript'>alert('Each attachment must be below 10MB.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
			exit();
		}

		$original_name = $_FILES['gold_sale_attachments']['name'][$file_index];
		$file_extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
		if (!in_array($file_extension, $allowed_extensions))
		{
			echo "<script type='text/javascript'>alert('Only PDF or image attachments are allowed.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
			exit();
		}

		$new_attachment_name = $gold_sale_ref_code . "_" . ($attachment_position + 1) . "_" . time() . "." . $file_extension;
		$target_file = $target_dir . basename($new_attachment_name);

		if (!move_uploaded_file($_FILES['gold_sale_attachments']['tmp_name'][$file_index], $target_file))
		{
			echo "<script type='text/javascript'>alert('Failed to upload attachment.');</script>";
			echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
			exit();
		}

		$uploaded_attachments[$attachment_position] = $new_attachment_name;
		$attachment_position++;
	}

	date_default_timezone_set("Asia/Kuala_Lumpur");
	$created_date = date('Y-m-d H:i:s');
	$status = 1;

	$mysqli->begin_transaction();

	$sql_wallet = "SELECT cash_wallet
				   FROM wallet
				   WHERE ref_code='$user_ref_code'
				   LIMIT 1";
	$result_wallet = $mysqli->query($sql_wallet);
	if (!$result_wallet || $result_wallet->num_rows == 0)
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Wallet not found.');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}

	$row_wallet = $result_wallet->fetch_assoc();
	$current_cash_wallet = (float)$row_wallet['cash_wallet'];
	$new_cash_wallet = (float)number_format($current_cash_wallet + $commission_amount, 2, '.', '');

	$query_gold_sales = "INSERT INTO gold_sales
	(
		gold_sale_ref_code,
		user_ref_code,
		emas_ref_code,
		emas_name,
		emas_price,
		emas_sale_profit_pergram,
		item_code,
		gold_weight,
		customer_full_name,
		customer_email,
		customer_phone_number,
		customer_address,
		sale_remark,
		attachment_1,
		attachment_2,
		attachment_3,
		commission_amount,
		trans_code,
		status,
		created_date
	)
	VALUES
	(
		'$gold_sale_ref_code',
		'$user_ref_code',
		'$emas_ref_code',
		'$emas_name',
		'$emas_price',
		'$emas_sale_profit_pergram',
		'$item_code',
		'$gold_weight',
		'$customer_full_name',
		'$customer_email',
		'$customer_phone_number',
		'$customer_address',
		'$sale_remark',
		'$uploaded_attachments[0]',
		'$uploaded_attachments[1]',
		'$uploaded_attachments[2]',
		'$commission_amount',
		'$trans_code',
		'$status',
		'$created_date'
	)";
	$result_gold_sales = $mysqli->query($query_gold_sales);

	$Update_wallet = "UPDATE wallet SET
	cash_wallet='$new_cash_wallet'
	WHERE ref_code='$user_ref_code'";
	$result_wallet_update = $mysqli->query($Update_wallet);

	$type_of_process = "Gold Sales Commission";
	$type_of_transaction = "CW";
	$in_transactions = $commission_amount;
	$out_transactions = 0;
	$description = $mysqli->real_escape_string("Gold Sales Commission | Sales ID: $gold_sale_ref_code | Gold: $emas_name | Item Code: $item_code | Weight: " . number_format($gold_weight, 2) . " gram | Profit Per Gram: RM " . number_format($emas_sale_profit_pergram, 2) . " | Customer: $customer_full_name");

	$query_transactions = "INSERT INTO transactions
	(
		user_ref_code,
		trans_code,
		type_of_process,
		type_of_transaction,
		in_transactions,
		out_transactions,
		balance,
		description,
		status,
		created_date
	)
	VALUES
	(
		'$user_ref_code',
		'$trans_code',
		'$type_of_process',
		'$type_of_transaction',
		'$in_transactions',
		'$out_transactions',
		'$new_cash_wallet',
		'$description',
		'$status',
		'$created_date'
	)";
	$result_transactions = $mysqli->query($query_transactions);

	if ($result_gold_sales && $result_wallet_update && $result_transactions)
	{
		$mysqli->commit();
		echo "<script type='text/javascript'>alert('Successfully Submit Gold Sales');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_view.php'; </script>";
		exit();
	}
	else
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Fail, Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='../U/gold_sales_add.php'; </script>";
		exit();
	}
}
?>

<?php
function getClientIp(): string
{
    // Cloudflare connecting IP (best if you use CF)
    if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    }

    // Common proxy headers (use first valid public IP)
    $candidates = [
        $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '',
        $_SERVER['HTTP_X_REAL_IP'] ?? '',
        $_SERVER['REMOTE_ADDR'] ?? '',
    ];

    foreach ($candidates as $ipList) {
        if (!$ipList) continue;

        // X_FORWARDED_FOR may contain "client, proxy1, proxy2"
        $parts = array_map('trim', explode(',', $ipList));
        foreach ($parts as $ip) {
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }

    // Fallback (could be private)
    return $_SERVER['REMOTE_ADDR'] ?? '';
}

function getCountryFromIp(string $ip): string
{
    // 1) If behind Cloudflare, this header is the easiest
    if (!empty($_SERVER['HTTP_CF_IPCOUNTRY']) && $_SERVER['HTTP_CF_IPCOUNTRY'] !== 'XX') {
        return strtoupper($_SERVER['HTTP_CF_IPCOUNTRY']); // e.g. "MY"
    }

    // 2) If IP empty or localhost/private
    if ($ip === '' || $ip === '127.0.0.1' || $ip === '::1') {
        return 'MY'; // choose your default for local testing
    }

    // 3) Call an IP geo service (simple + free). Keep timeout short.
    $url = "http://ip-api.com/json/" . urlencode($ip) . "?fields=status,countryCode";

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 2,
        CURLOPT_TIMEOUT => 3,
        CURLOPT_FAILONERROR => false,
    ]);

    $resp = curl_exec($ch);
    curl_close($ch);

    if ($resp) {
        $data = json_decode($resp, true);
        if (is_array($data) && ($data['status'] ?? '') === 'success' && !empty($data['countryCode'])) {
            return strtoupper($data['countryCode']); // "MY", "SG", etc.
        }
    }

    // 4) Fallback
    return 'MY';
}
?>
