<?php session_start();?>
<?php error_reporting(0);?>

<!--Connection start here-->
<?php include_once("../Header/Connection.php"); ?>
<!--Connect end here-->

<?php

$user_id = $_SESSION['id'];
$sponsor_code=$_SESSION['sponsor_code'];
$ref_code=$_SESSION['ref_code'];
$level = $_SESSION['level'];
$rank = $_SESSION['rank'];
$email=$_SESSION['email'];
$name=$_SESSION['name'];
$phone_number=$_SESSION['phone_number'];
$profile_image=$_SESSION['profile_image'];
$type_of_user=$_SESSION['type_of_user'];
$activation_status=$_SESSION['activation_status'];

if (!isset($_SESSION['ref_code'])) 
{
 echo "<script type='text/javascript'> document.location='https://mygoldsdnbhd.com/log-masuk/'; </script>";
} 
?>

<!DOCTYPE html>
<html lang="en">
<?php include ("../Header/head.php"); ?>
<body class="skin-default fixed-layout">

<!-- Main wrapper - style you can find in pages.scss -->
<div id="main-wrapper">    
<?php include ("../Header/header.php"); ?>
<?php include ("../Header/left_menu.php"); ?>
<?php include ("../Header/right_sidebar.php"); ?>
        
<!-- Page wrapper  -->
<div class="page-wrapper">
<!-- Container fluid  -->
<div class="container-fluid">
<!-- Bread crumb and right sidebar toggle -->
<!--?php include ("../Header/breadcumb.php"); ?-->
<br><br>
<!-- End Bread crumb and right sidebar toggle -->
    
<!-- Start Page Content -->
<!-- ============================================================== -->

<?php
$user_ref_code = $_GET['user_ref_code'];

if ( $level != '1')
{
    if ($user_ref_code != $ref_code)
    {
        echo "<script type='text/javascript'>alert('You can't view other user profile');</script>";
        echo "<script type='text/javascript'> document.location='user_dashboard.php'; </script>";
		exit();
	}
}

$sql_user = "SELECT *
FROM user
WHERE ref_code='$user_ref_code'
And status='1'
LIMIT 1";
$result_user = $mysqli->query($sql_user);
if ($result_user->num_rows > 0)
{
while($row_user = $result_user -> fetch_assoc())
{                
$id = $row_user['id'];
$ref_code = $row_user['ref_code'];
$nick_name = $row_user['nick_name'];
$username = $row_user['username'];
$helper_code = $row_user['helper_code'];
$sponsor_code = $row_user['sponsor_code'];
$sponsor_last_name = $row_user['sponsor_last_name'];
$user_level = $row_user['level'];
$manager_level = $row_user['manager_level'];
$type_of_user = $row_user['type_of_user'];
$rank = $row_user['rank'];
$name = $row_user['name'];
$last_name = $row_user['last_name'];
$email = $row_user['email'];
$password = $row_user['password'];
$phone_number = $row_user['phone_number'];
$phone_number_2 = $row_user['phone_number_2'];
$no_ic = $row_user['no_ic'];
$ic_front = $row_user['ic_front'];
$ic_back = $row_user['ic_back'];
$address = $row_user['address'];
$address_2 = $row_user['address_2'];
$state = $row_user['state'];
$area = $row_user['area'];
$postcode = $row_user['postcode'];
$country = $row_user['country'];
$birth_date = $row_user['birth_date'];
$bank_type = $row_user['bank_type'];
$acc_no = $row_user['acc_no'];
$acc_holder = $row_user['acc_holder'];
$deposit_rm_individual = $row_user['deposit_rm'];
$heir_name = $row_user['heir_name'];
$heir_ic = $row_user['heir_ic'];
$heir_phone_number = $row_user['heir_phone_number'];
$deposit_rm_individual = $row_user['deposit_rm'];
$purchase_status = $row_user['purchase_status'];
$spouse_status = $row_user['spouse_status'];
$wallet_status = $row_user['wallet_status'];
$status = $row_user['status'];
$activation_status = $row_user['activation_status'];
$verification_status = $row_user['verification_status'];
$withdraw_block_status = $row_user['withdraw_block_status'];
$created_date = $row_user['created_date'];	

$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'];
}

$sql_sponsor = "SELECT * 
FROM user
WHERE ref_code='$sponsor_code'
And status='1'";
$result_sponsor = $mysqli->query($sql_sponsor);
if ($result_sponsor->num_rows > 0)
{
    $row_sponsor = $result_sponsor->fetch_assoc();		
    $sponsor_nick_name = $row_sponsor['nick_name'];
	$sponsor_name = $row_sponsor['name'];
    
}

if ($deposit_rm_individual == '0')
{
    $deposit_rm = $deposit_rm;
}
else
{
    $deposit_rm = $deposit_rm_individual;
}


if ($withdraw_block_status == "0")
{
    $withdraw_block_status_display = "Enable";
}
else
if ($withdraw_block_status == "1")
{
    $withdraw_block_status_display = "Disable";
}


if ($activation_status == '0')
{
    $activation_status_display = 'Unactive';
} 
else
if ($activation_status == '1')
{
    $activation_status_display = 'Active';
}


if ($verification_status == '0')
{
    $verification_status_display = 'Not Verified';
} 
else
if ($verification_status == '1')
{
    $verification_status_display = 'Verified';
}

if ($ic_front == "" &&  $ic_back == "")
{
    $reminder = "| Please Upload Your Front And Back IC For Verification And Full Access";
}

?> 

<div class="row">
<div class="col-lg-12">
<div class="card">
    <div class="card-body">
        <form method="post" action="" onsubmit="return confirm('Do you want to proceed?');" enctype="multipart/form-data">
            <div class="form-body">
                <h3 class="card-title">User Profile <?php echo $reminder; ?></h3>
                <hr>
                                        
                <div class="row p-t-20">                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Front IC ..</label>
                            <?php if ($ic_front != "")
                            {
                            ?>
                            | <a href="../Controller/uploads/<?php echo $ic_front; ?>" download><font color="blue">Download</font></a> 
                            <br> 
                            <img src="../Controller/uploads/<?php echo $ic_front; ?>" width="100" height="100" class="img-circle">
                            <?php
							}
                            ?>
                            <br><br>
                            <b><font size="1px">Only Jpg, Jpeg and Png file allow to be upload</font></b>
                            <input type="file" class="form-control" name="ic_front">
                        </div>
                    </div> 
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Back IC</label>
                             <?php if ($ic_back != "")
                            {
                            ?>
                            | <a href="../Controller/uploads/<?php echo $ic_back; ?>" download><font color="blue">Download</font></a> 
                            <br>  
                            <img src="../Controller/uploads/<?php echo $ic_back; ?>" width="100" height="100" class="img-circle">
                            <?php
							}
                            ?> 
                            <br><br>
                            <b><font size="1px">Only Jpg, Jpeg and Png file allow to be upload</font></b>
                            <input type="file" class="form-control" name="ic_back">
                        </div>
                    </div>                     

                    <?php if ($level == "1")
                    {
                    ?>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="control-label">Member Withdrawal Status</label>                                                   
                                <select name="withdraw_block_status" class="form-control">
                                <option value="<?php echo $withdraw_block_status; ?>"><?php echo $withdraw_block_status_display; ?></option>
                                <option value="0">Enable</option>
                                <option value="1">Disable</option>
                                </select>
                            </div>
                        </div>

                    <?php
					}
                    ?>                   

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Username</label>
                            <input type="text" name="nick_name" class="form-control" value="<?php echo $nick_name; ?>" readonly>
                        </div>
                    </div>

                    <?php if ($activation_status == '1')
                    {
                    ?>
                         <div class="col-md-6">
                            <div class="form-group">
                                <label class="control-label">Refferal Link</label> 
                                <!--button onclick="myFunction()">Copy text</button-->

                                <input id="myInput" type="text" class="form-control" 
                                value="https://mygoldsdnbhd.com/pendaftaran/?username=<?php echo rawurlencode($nick_name); ?>" readonly>

                                <script>
                                function myFunction() 
                                {
                                    var copyText = document.getElementById("myInput");
                                    copyText.select();
                                    copyText.setSelectionRange(0, 99999)
                                    document.execCommand("copy");
                                    alert("Copied the text: " + copyText.value);
                                }
                                </script>
                            </div>
                        </div>
                    <?php
					}
                    ?>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Sponsor ID</label> ( <?php echo $sponsor_nick_name; ?> | <?php echo $sponsor_name; ?> )
                            <input type="text" class="form-control" value="<?php echo $sponsor_code; ?>" readonly>
                        </div>
                    </div>

                    <?php if ($level == '1')
                    {
                    ?>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Change Sponsor ID</label>
                            <select name="new_sponsor_ref_code" class="form-control">
                            <option value="">Select New Sponsor</option>
                            <?php
                            $q_level = "SELECT * 
                            FROM user 
                            Where  status='1'
                            And activation_status='1'
                            order by id Asc";
                            $result_level = $mysqli-> query($q_level);
                            if ($result_level -> num_rows > 0)
                            {
	                            while($row_level = $result_level -> fetch_assoc())
	                            {   
                                $id = $row_level['id'];
                                $new_sponsor_ref_code = $row_level['ref_code'];
                                $new_sponsor_name = $row_level['name'];
                                $new_sponsor_type_of_user = $row_level['type_of_user'];
                                ?>
                                <option value="<?php echo $new_sponsor_ref_code; ?>"><?php echo $new_sponsor_ref_code; ?> | <?php echo $new_sponsor_name; ?> | <?php echo $new_sponsor_type_of_user; ?></option>
                                <?php
                                }
                            }
                            ?>
                            </select>
                        </div>
                    </div>

                    <?php
					}
                    ?>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Your Refferal ID</label>
                            <input type="text" class="form-control" name="ref_code" value="<?php echo $ref_code; ?>" readonly>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Manager Level</label>
                            <select name="manager_level" class="form-control" <?php if ($level != '1') { echo 'disabled'; } ?>>
                                <?php if ($manager_level != "") { ?>
                                <option value="<?php echo htmlspecialchars($manager_level, ENT_QUOTES); ?>"><?php echo htmlspecialchars($manager_level, ENT_QUOTES); ?></option>
                                <?php } else { ?>
                                <option value="">Select Manager Level</option>
                                <?php } ?>
                                <?php
                                $q_manager_level = "SELECT *
                                                    FROM `Manager_Level_Setting`
                                                    WHERE status='1'
                                                    ORDER BY id ASC";
                                $result_manager_level = $mysqli->query($q_manager_level);
                                if ($result_manager_level && $result_manager_level->num_rows > 0)
                                {
                                    while($row_manager_level = $result_manager_level->fetch_assoc())
                                    {
                                        $manager_level_name = $row_manager_level['name_of_level'];
                                        if ($manager_level_name == $manager_level)
                                        {
                                            continue;
                                        }
                                ?>
                                <option value="<?php echo htmlspecialchars($manager_level_name, ENT_QUOTES); ?>"><?php echo htmlspecialchars($manager_level_name, ENT_QUOTES); ?></option>
                                <?php
                                    }
                                }
                                ?>
                            </select>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Email</label>
                            <input type="text" class="form-control"  name="email" value="<?php echo $email; ?>" <?php  if ( $level == '1') { ;?> required <?php } else { ;?> readonly <?php } ?>>
                        </div>
                    </div>

                    <?php
                    if ( $level == '1')
                    {
                    ?>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="control-label">Password</label>
                                <input type="text" class="form-control"  name="password" value="<?php echo $password; ?>" >
                            </div>
                        </div>
                    <?php
					}
                    ?>
                    
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">First Name</label>
                            <input type="text" class="form-control"  name="name" value="<?php echo $name; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Last Name</label>
                            <input type="text" class="form-control"  name="last_name" value="<?php echo $last_name; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">IC NO</label>
                            <input type="text" class="form-control"  name="no_ic" value="<?php echo $no_ic; ?>" >
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Birth Date</label>
                            <input type="date" class="form-control"  name="birth_date" value="<?php echo $birth_date; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Phone Number</label>
                            <input type="text" class="form-control"  name="phone_number" value="<?php echo $phone_number; ?>" >
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Address</label>
                            <textarea type="text"  style="width:100%;" rows="2" cols="39" name="address"><?php echo $address; ?>
                            </textarea>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Address 2</label>
                            <textarea type="text"  style="width:100%;" rows="2" cols="39" name="address_2"><?php echo $address_2; ?>
                            </textarea>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Country</label>
                            <input type="text" class="form-control"  name="country" value="<?php echo $country; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">State</label>
                            <input type="text" class="form-control"  name="state" value="<?php echo $state; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Postcode</label>
                            <input type="text" class="form-control"  name="postcode" value="<?php echo $postcode; ?>" >
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Type Of Bank</label>
                            <select  name="bank_type" id="select" class="form-control" >
								<?php include("../Extra/Bank.php"); ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Account Bank Number</label>
                            <input type="text" class="form-control"  name="acc_no" value="<?php echo $acc_no; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Account Holder Name</label>
                            <input type="text" class="form-control"  name="acc_holder" value="<?php echo $acc_holder; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Heir Name</label>
                            <input type="text" class="form-control"  name="heir_name" value="<?php echo $heir_name; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Heir IC No.</label>
                            <input type="text" class="form-control"  name="heir_ic" value="<?php echo $heir_ic; ?>" >
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label">Heir Phone Number</label>
                            <input type="text" class="form-control"  name="heir_phone_number" value="<?php echo $heir_phone_number; ?>" >
                        </div>
                    </div>

                </div>
            </div>
            <div class="form-actions">
                <input type="hidden" class="form-control"  name="id" value="<?php echo $id; ?>">
                <input type="hidden" class="form-control"  name="ref_code" value="<?php echo $user_ref_code; ?>">
                <input type="hidden" class="form-control"  name="from_page" value="user_detail.php">
                <input type="hidden" class="form-control"  name="activation_way" value="activation_wallet">

                <button name="Update_User_Detail" class="btn btn-success"><i class="fa fa-check"></i> Update</button>        

                <?php if ($level == '1' && $verification_status == '0')// If user status not activate baru tunjuk button ni
                {
                ?>
                

                <br><br><br><br>
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="control-label">Rejection Message</label>
                        <input type="text" class="form-control"  name="rejection_message" >
                    </div>
                </div>
                <button name="verified_new_user" class="btn btn-success"><i class="fa fa-check"></i> Verified Member</button>
                <button name="reject_verificaion_new_user" class="btn btn-success"><i class="fa fa-check"></i> Reject Member Verification</button>
                <?php
				}
                ?>
                
            </div>
        </form>
    </div>
</div>
</div>
</div>
<?php
}
}
else
{
echo mysql_error();
}
?>						
<!-- ============================================================== -->
<!-- End PAge Content -->

</div>
<!-- End Container fluid  -->
</div>
<!-- End Page wrapper  -->

<!-- Footer Start-->
<?php include ("../Footer/footer.php"); ?>
<!-- Footer End-->

</div>
<!-- End Wrapper -->
<!-- All Jquery -->
    

<!-- All Jquery Start-->
<?php include ("../Header/all_jquery.php"); ?>
<!-- All Jquery End-->

</body>

</html>



<?php
if (isset($_POST['Update_User_Detail'])) 
{
	//echo "<script type='text/javascript'>alert('In');</script>";
    $ref_code = $_POST['ref_code'];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	$deposit_rm1 = $_POST['deposit_rm'];
    $deposit_rm_individual  = htmlspecialchars($deposit_rm1, ENT_QUOTES);

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

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

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

	$withdraw_block_status = $_POST['withdraw_block_status'];

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

    $manager_level_update = "";
    if ($level == '1')
    {
        $manager_level1 = $_POST['manager_level'] ?? "";
        $manager_level  = htmlspecialchars($manager_level1, ENT_QUOTES);
        $manager_level_update = "manager_level ='$manager_level',";
    }

	date_default_timezone_set("Asia/Kuala_Lumpur");

	$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'];

		if ($deposit_rm_individual == "")
		{
			$deposit_rm_individual = $deposit_rm;
		}
	}

	$mysqli->begin_transaction();

	if ($_FILES['ic_front']['size'] != 0 )
	{
		$target_dir = "../Controller/uploads/";
		$time_stamp = time();
		$temp1 = $temp1 = explode(".", $_FILES["ic_front"]["name"]);
		$newfilename1 = $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["ic_front"]["tmp_name"]);
			if( ($check1 !== false) )
			{
				echo "File is an Image - " . $check1["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				$mysqli->rollback();
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
				echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
				exit();
			}
		}

		// Allow certain file formats
		if($imageFileType1 != "jpg" && $imageFileType1 != "JPG" && $imageFileType1 != "png" && $imageFileType1 != "PNG" && $imageFileType1 != "jpeg" && $imageFileType1 != "JPEG")
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, only JPG, JPEG, PNG files are allowed.');</script>";
		    $uploadOk = 0;
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
		}

		// Check if file already exists
		if ( (file_exists($target_file1)) )
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
			// if everything is ok, try to upload file
		}
		else
		{
			if (move_uploaded_file($_FILES["ic_front"]["tmp_name"], $target_file1))
			{
				$ic_front = $ref_code . $time_stamp. '1.' . end($temp1);



				$UpdateQuery = "UPDATE user SET 
				ic_front='$ic_front'
				WHERE ref_code='$ref_code' ";
				$result = $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='user_detail.php?user_ref_code=$ref_code'; </script>";
				exit();
			}
		}
	}

	if ($_FILES['ic_back']['size'] != 0 )
	{
		$target_dir2 = "../Controller/uploads/";
		$time_stamp = time();
		$temp2 = $temp2 = explode(".", $_FILES["ic_back"]["name"]);
		$newfilename2 = $ref_code . $time_stamp. '2.' . end($temp2);
		$target_file2 = $target_dir2 . basename($newfilename2);
		$uploadOk = 1;
		$imageFileType2 = pathinfo($target_file2,PATHINFO_EXTENSION);

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

			$check2 = getimagesize($_FILES["ic_back"]["tmp_name"]);
			if( ($check2 !== false) )
			{
				echo "File is an Image - " . $check2["mime"] . ".";
				$uploadOk = 1;
			} 
			else 
			{
				$mysqli->rollback();
				echo "<script type='text/javascript'>alert('File is not an Image.');</script>";
				$uploadOk = 0;
				echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
				exit();
			}
		}

		// Allow certain file formats
		if($imageFileType2 != "jpg" && $imageFileType2 != "JPG" && $imageFileType2 != "png" && $imageFileType2 != "PNG" && $imageFileType2 != "jpeg" && $imageFileType2 != "JPEG")
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, only JPG, JPEG, PNG files are allowed.');</script>";
		    $uploadOk = 0;
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
		}

		// Check if file already exists
		if ( (file_exists($target_file2)) )
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, file already exists.');</script>";
			$uploadOk = 0;
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
		}

		// Check if $uploadOk is set to 0 by an error
		if ($uploadOk == 0)
		{
			$mysqli->rollback();
			echo "<script type='text/javascript'>alert('Sorry, your file was not uploaded.');</script>";
			echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
			exit();
			// if everything is ok, try to upload file
		}
		else
		{
			if ( move_uploaded_file($_FILES["ic_back"]["tmp_name"], $target_file2)  )
			{
				$ic_back = $ref_code . $time_stamp. '2.' . end($temp2);

				$UpdateQuery = "UPDATE user SET 
				ic_back='$ic_back'
				WHERE ref_code='$ref_code' ";
				$result = $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='user_detail.php?user_ref_code=$ref_code'; </script>";
				exit();
			}
		}
	}

	// ===============================
    // Sponsor change: revert & re-pay
    // ===============================
    if ($new_sponsor_ref_code != "") 
    {
        // 0) Get OLD sponsor (before update)
        $oldSponsorRes = $mysqli->query("SELECT sponsor_code FROM user WHERE ref_code='$ref_code' AND status='1' LIMIT 1");
        $old_sponsor_ref_code = "";
        if ($oldSponsorRes && $oldSponsorRes->num_rows > 0) {
            $old_sponsor_ref_code = $oldSponsorRes->fetch_assoc()['sponsor_code'] ?? "";
        }

        // Only proceed if sponsor really changed
        if ($old_sponsor_ref_code != "" && $old_sponsor_ref_code != $new_sponsor_ref_code) {

            // 1) Update sponsor in user table (your existing logic)
            $sql_sponsor = "SELECT user_id FROM user WHERE ref_code='$new_sponsor_ref_code' AND status='1' LIMIT 1";
            $result_sponsor = $mysqli->query($sql_sponsor);
            $new_sponsor_id = 0;
            if ($result_sponsor && $result_sponsor->num_rows > 0) {
                $new_sponsor_id = (int)($result_sponsor->fetch_assoc()['user_id'] ?? 0);
            }

            $resUpdate_User_Sponsor = $mysqli->query("
                UPDATE user
                SET sponsor_code='$new_sponsor_ref_code',
                    sponsor_id='$new_sponsor_id'
                WHERE ref_code='$ref_code'
            ");
            if (!$resUpdate_User_Sponsor) {
                $mysqli->rollback();
                echo "<script>alert('Fail to update sponsor.');</script>";
                echo "<script>document.location='user_detail.php?user_ref_code=$ref_code';</script>";
                exit();
            }

            // 2) Get ALL orders of this member (the purchaser)
            $ordersRes = $mysqli->query("
                SELECT order_id, trans_code, order_items
                FROM woocommerce_order_info
                WHERE status='1'
                  AND new_ref_code='$ref_code'
                ORDER BY id ASC
            ");

            if ($ordersRes && $ordersRes->num_rows > 0) 
            {
                while ($o = $ordersRes->fetch_assoc()) 
                {

                    $order_id_x   = $o['order_id'];
                    $trans_code_x = $o['trans_code'];
                    $order_items_x = $o['order_items'];

                    // 3) Find all commission txns created for this order trans_code
                    //    (these are the payouts to uplines)
                    $txnRes = $mysqli->query("
                        SELECT id, user_ref_code, in_transactions
                        FROM transactions
                        WHERE status='1'
                          AND trans_code='$trans_code_x'
                          AND (
                                type_of_process='bonus_sponsor'
                                OR type_of_process LIKE 'hibah_unilevel_level_%'
                              )
                    ");

                    // 4) Revert each commission: deduct wallet + insert reverse txn + mark old txn status=9
                    if ($txnRes && $txnRes->num_rows > 0) {
                        while ($t = $txnRes->fetch_assoc()) {

                            $txn_id = (int)$t['id'];
                            $agent_ref = $t['user_ref_code'];
                            $amt = (float)($t['in_transactions'] ?? 0);

                            if ($amt <= 0) continue;

                            // get agent wallet
                            $wRes = $mysqli->query("SELECT cash_wallet FROM wallet WHERE ref_code='$agent_ref' LIMIT 1");
                            if (!$wRes || $wRes->num_rows == 0) continue;

                            $currBal = (float)$wRes->fetch_assoc()['cash_wallet'];
                            $newBal  = (float)number_format($currBal - $amt, 2, '.', '');

                            // update wallet
                            $uW = $mysqli->query("UPDATE wallet SET cash_wallet='$newBal' WHERE ref_code='$agent_ref'");
                            if ($uW === false) {
                                $mysqli->rollback();
                                echo "<script>alert('Fail revert wallet for $agent_ref');</script>";
                                echo "<script>document.location='user_detail.php?user_ref_code=$ref_code';</script>";
                                exit();
                            }

                            // insert reverse transaction
                            $created_dt = date('Y-m-d H:i:s');
                            $descRev = "Revert commission USD ".number_format($amt,2)." due to sponsor change for Order ID:$order_id_x";
                            $insRev = $mysqli->query("
                                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', '$trans_code_x', 'revert_commission', 'Out', '0', '$amt', '$newBal', '".$mysqli->real_escape_string($descRev)."', '1', '$created_dt')
                            ");
                            if ($insRev === false) {
                                $mysqli->rollback();
                                echo "<script>alert('Fail insert revert transaction');</script>";
                                echo "<script>document.location='user_detail.php?user_ref_code=$ref_code';</script>";
                                exit();
                            }

                            // mark old commission txn as cancelled (optional but strongly recommended)
                            $mysqli->query("UPDATE transactions SET status='9' WHERE id='$txn_id' LIMIT 1");
                        }
                    }

                    // 5) Re-pay commissions based on NEW sponsor using woocommerce_order_info_item rows
                    $itemsRes = $mysqli->query("
                        SELECT item_total_price, item_name, item_nilai_mata
                        FROM woocommerce_order_info_item
                        WHERE status='1'
                          AND order_id='$order_id_x'
                        ORDER BY id ASC
                    ");

                    if ($itemsRes && $itemsRes->num_rows > 0) {
                        while ($it = $itemsRes->fetch_assoc()) {
                            $base_amount = (float)$it['item_total_price'];
                            if ($base_amount <= 0) continue;

                            $pkg_ref_code = $it['item_nilai_mata'] ?? '';
                            $pkgSetting = getPackageCommissionSetting($mysqli, $pkg_ref_code);

                            $ok = distributeCommissionCompressed(
                                $mysqli,
                                $new_sponsor_ref_code,                 // <-- NEW sponsor starts here
                                $base_amount,
                                $trans_code_x,
                                (int)$order_id_x,
                                "Sponsor Change | " . ($it['item_name'] ?? $order_items_x),
                                $pkgSetting
                            );

                            if (!$ok) {
                                $mysqli->rollback();
                                echo "<script>alert('Fail to re-run commission for Order ID:$order_id_x');</script>";
                                echo "<script>document.location='user_detail.php?user_ref_code=$ref_code';</script>";
                                exit();
                            }
                        }
                    }
                }
            }
        }
    }

	$Update_User_Detail = "UPDATE user SET 
	nick_name ='$nick_name',
	name ='$name',
	last_name ='$last_name',
	email ='$email',	
    no_ic ='$no_ic',	
	birth_date ='$birth_date',
	phone_number ='$phone_number',
	address ='$address',
	address_2 ='$address_2',
	country ='$country',
	state ='$state',
	postcode ='$postcode',
	bank_type ='$bank_type',
	acc_no ='$acc_no',
	acc_holder ='$acc_holder',
    heir_name ='$heir_name',
    heir_ic ='$heir_ic',
    heir_phone_number ='$heir_phone_number',
	$manager_level_update
	withdraw_block_status ='$withdraw_block_status'
	WHERE ref_code ='$ref_code'";
	$resUpdate_User_Detail = $mysqli->query($Update_User_Detail);

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

		//Email to verify user
		if ( ($_FILES['ic_back']['size'] != 0) && ($_FILES['ic_front']['size'] != 0))
		{
			/********************** Email To HQ *************************************************/
			$hq_email = "mygoldplt_websystemmabrur@gmail.com";
			$to_hq = $hq_email;
			$subject_hq = "Hi $hq_email, mygoldsdnbhd.com Account Verification Request $ref_code | $name";
        
			$message_hq = "
			<html>
			<head>
			<title>Hi $hq_email, mygoldsdnbhd.com Account Verification Request $ref_code | $name</title>
			</head>
			<body>
			<p>

			Hai $hq_email,<br><br>

			mygoldsdnbhd.com Account Verification Request for $ref_code | $name  <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 User Start*************************************************/
            /*
			$message = "RM0 UMRAH HAJI MABRUR SDN BHD: mygoldsdnbhd.com Account Verification Request for $ref_code | $name";
			$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('Succesfully Update');</script>";
        echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
		exit();
	} 
	else 
	{
		$mysqli->rollback();
		echo "<script type='text/javascript'>alert('Please Try Again');</script>";
		echo "<script type='text/javascript'> document.location='user_detail.php?user_ref_code=$ref_code'; </script>";
		exit();
	}
}
?>
