<?PHP
$_OPTIMIZATION["title"] = $lang['payment']['title'];
$usid = $_SESSION["user_id"];
$usname = $_SESSION["user"];
$db->Query("SELECT * FROM db_users_b WHERE id = '$usid' LIMIT 1");
$user_data = $db->FetchArray();
$deposit=$user_data["deposit_address"];
$db->Query("SELECT * FROM db_config WHERE id = '1' LIMIT 1");
$sonfig_site = $db->FetchArray();
$status_array = array( 0 => "Checked", 1 => "Выплачивается", 2 => "Canceled", 3 => "Paid");
# Минималка серебром!
$minPay = 0.000001;

$minValueswap = 0.0001;
function getUserIP() {
    if( array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',')>0) {
            $addr = explode(",",$_SERVER['HTTP_X_FORWARDED_FOR']);
            return trim($addr[0]);
        } else {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

function checkEmail($email) {
   $find1 = strpos($email, '@');
   $find2 = strpos($email, '.');
   return ($find1 !== false && $find2 !== false );
} 

include('./faucetpay.php');
$fp = new FaucetPay('960cd82ad33bdb033f45116a3dc28b1317a797c0');



//echo(getUserIP());

 
if (strlen($user_data["deposit_address"])< 5){
	$api_key = 'DL8ZuXstdYfD1Ha8sWeOx4Dcj4lxcGLrEkHqVU9uXFU';
$url = 'https://bch.blockonomics.co/api/new_address';

$options = array( 
    'http' => array(
        'header'  => 'Authorization: Bearer '.$api_key,
        'method'  => 'POST',
        'content' => '',
        'ignore_errors' => true
    )   
);  

$context = stream_context_create($options);
$contents = file_get_contents($url, false, $context);
$object = json_decode($contents);

// Check if address was generated successfully
if (isset($object->address)) {
  echo $object->address;
  
  $address=$object->address;
  $db->Query("UPDATE db_users_b SET deposit_address = '$address' WHERE id = '$usid'");
  
} else {
  // Show any possible errors
  echo $http_response_header[0]."\n".$contents;
}
	
	
	
}

?>
<section class="no-padding-bottom">
    <div class="col-lg-12">
        <div class="card">
		
            <div class="card-body">
                <?PHP
                    # Заносим выплату
                    if(isset($_POST["purse"])){
                        //$purse = $func->validatePurse($_POST["purse"]);
						$validpurse=checkEmail($_POST["purse"]);
						
                        $sum = floatval($_POST["sum"]);
                        $val = "BCH";
                        if($validpurse){
							$purse=$_POST["purse"];
							$response = $fp->checkaddress(
	array(
		"currency" => "BCH",
		"address" => $purse
	)
);
if ($response["status"]==200){
                            if($sum >= $minPay){
								$sum_pay = $sum * 0.95;
                                if($sum_pay <= $user_data["bch_withdrawal"]){
                                    # Проверяем на существующие заявки
                                    $db->Query("SELECT COUNT(*) FROM db_payment WHERE user_id = '$usid' AND (status = '0' OR status = '1')");
                                    if($db->FetchRow() == 0){
                                        ### Делаем выплату ###
                                        
                                                $sum_pay = $sum * 0.95;
                                                
                                                $response = $fp->send(
	array(
		"currency" => "BCH",
		"amount" => $sum_pay *100000000 ,
		"to" => $purse ,
		"ip_address" => getUserIP()
		
	)
);


if ($response["message"]=="OK"){

                                                    
                                                    
                                                        # Снимаем с пользователя
                                                        $db->Query("UPDATE db_users_b SET bch_withdrawal = bch_withdrawal - '$sum' WHERE id = '$usid'");
                                                        # Вставляем запись в выплаты
                                                        $da = time();
                                                        $dd = $da + 60*60*24*15;
                                                        
                                                        $db->Query("INSERT INTO db_payment (user, user_id, purse, sum, valuta, serebro, date_add, status) VALUES ('$usname','$usid','$purse','$sum_pay','BCH', '$sum','".time()."', '3')");
                                                        $db->Query("UPDATE db_users_b SET payment_sum = payment_sum + '$sum_pay' WHERE id = '$usid'");
                                                        $db->Query("UPDATE db_stats SET all_payments = all_payments + '$sum_pay' WHERE id = '1'");
                                                        $message=$lang['payment']['success'];
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',1,6000); }); </script>";
														
}                        
                                                    
                                                
                                        
                                    }else {
										$message=$lang['payment']['errorWait'];
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";}
            
									
									}
                                else {
									$message=$lang['payment']['errorMax'];
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						}
            
									
									
								}
                            else {
								
							$message = sprintf($lang['payment']['errorMin'],$minPay,'BCH'); 
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						}
                        }
						
						
						else {
							$message="This email is not linked to faucetpay.io";
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						}
					}
					
					else {
							$message='Please add a valid email';
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						}
						
					
						
                    }
                ?>
            </div>
        </div>
    </div>
</section>

<section class="main races">
    <div class="wrapper-constrained">
        <div class="content-wrapper flex">
            <div class="perfpage">
                                <div class="pinfo">
                    <div class="picon"></div>
                    <div class="pcont">
					    <p>Deposit Bonus : <strong>+ 20% ! </strong> You can deposit the amount you like </p>
                        <p>You can withdraw your cash from the game any time, min 0.000001 BCH, transfer fee is 5% throught FaucetPay.io </p>

						</div>
                </div>
                                <div class="container elven">
                    <div class="decor big"></div>
                    <h3><span>Deposit/Withdraw Money</span></h3>
					

                    <div class="container-inner">

                        <?php if ($usid==1) { ?>
		
		<?php } ?>
                        
                        <div class="payments-container">  
					<p style="text-align:center"><span style="font-size:16px"><span style="color:#c0392b"><span style="font-family:Georgia,serif"><strong>35 % Commission for investment&nbsp;greater than 0.2 BCH !</strong></span></span></span></p>
						
                                <h2>Directly Deposit</h2>
							
								<p>You can send any amount of bitcoin cash to your deposit address :</p>
								<div data-bn-type="text"<label id="myInput"><?php echo $deposit ; ?></label></div>
								<button onclick="myFunction()">Copy address</button>

		
								<p>Money received will be added to your balance game after 2 network confirmations </p>
								
								<h2>Faucetpay Deposit</h2>
								<p>You can use other crypto in your faucetpay account to pay in BCH  </p>
								
								<p>Please precise the amount in BCH and click on the Button </p>
								
								<form action="https://faucetpay.io/merchant/webscr" method="post">
    <input type="hidden" name="merchant_username" value="aminessam">
    
    <input  type="hidden" name="item_description" value="Deposit In CashEmpire.cc">
    
    <input type="text" name="amount1" value="0.5">
    <br>
    <input type="hidden"  name="currency1" value="BCH">
	<input type="hidden"  name="currency2" value="BCH">
    
    
    <input type="hidden" name="custom" value="<?php echo $usid ; ?> ">
    
    <input type="hidden"  name="callback_url" value="https://cashempire.cc/faucetpayio.php">
    
    <input type="hidden"  name="success_url" value="https://cashempire.cc/">
    
    <input type="hidden" name="cancel_url" value="https://cashempire.cc/account/payment">
    
    <input type="submit" name="submit" value="Make Payment with FaucetPay">
</form>

								
								<h2>Deposit using Card or Bitcoin with Changely </h2>
								<script src="https://changelly.com/static/payment-button-widget/widget-modal.js"></script>
      <iframe src="https://changelly.com/static/payment-button-widget/index.html?paymentButtonTheme=default&buttonTextId=003&widgetLink=https%3A%2F%2Fwidget.changelly.com%3Ffrom%3Dusd%252Ceur%252Cbtc%252Ceth%26to%3Dbch%26amount%3D100%26address%3D%26fromDefault%3Dusd%26toDefault%3Dbch%26merchant_id%3DKBRVoM1MvJVn2fVs%26payment_id%3D%26v%3D3&isPopUp=true&tickerId=008
  " width="220" height="56" frameborder="0" style="border-radius: 4px"></iframe>
      <link rel="stylesheet" href="https://changelly.com/static/payment-button-widget/widget-modal.css"/>
      <div id="changellyModal"></div>
								
                                   <div id="cashout" class="st-center">
								   
                                    <h2>Withdrawal</h2>
                                    
                                    
                                    <div class="cashout_block padding-b" style="display: block">
                                    	<div class="elf_character"></div>
                                    	<div class="human_character"></div>
                                    	
                                                                                 
                                        <p><img src="/images/bch.png"></p>
                                        <p style="line-height: 1em"><a href="https://bitcoincash.org/" target="blank" ><small>More informations about Bitcoin Cash</small> </a>
										</p>
										
     
	  
      
    
                                        <form class="cashout_form" id="payeer_cashout" name="cashout_form" action="" method="post">
                                            <div class="form-row">
                                                <label>Amount to withdraw: <i class="ic-gold3"></i></label>
                                                                                                <input type="text" id="psumm" name="sum" placeholder="" value="<?php echo round($user_data["bch_withdrawal"],8) ;?>">
                                                                                                 <label>Your Email of faucetpay.io: </label>
																								 <input type="text" id="psumm" name="purse" placeholder="" >
																								 <br>
<button type="submit" name="swap" class="btn btn-small mt5"><?php echo $lang["btn"]['withdraw']; ?></button>
                                                                                            </div>
                                                                                    </form>
																					
																					
																					
																					<?PHP
                if(isset($_POST["sumswap"])){
                    $sumswap = floatval($_POST["sumswap"]);
                    if($sumswap >= $minValueswap){
                        if($user_data["bch_withdrawal"] >= $sumswap){
                            $add_sum = 1.2* $sumswap;
                            $ta = time();
                            $td = $ta + 60*60*24*15;
                            $db->Query("UPDATE db_users_b SET bch_buy = bch_buy + $add_sum, bch_withdrawal = bch_withdrawal - $sumswap WHERE id = '$usid'");
                            $db->Query("INSERT INTO db_swap_ser (user_id, user, amount_b, amount_p, date_add, date_del) VALUES ('$usid','$usname','$add_sum','$sumswap','$ta','$td')");
                            
									$message="Amount exchanged with success!";
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',1,6000); }); </script>";
						
							
                        }else {
							
									$message="There is not enough funds to exchange!";
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						
							
						}
							
						
						
                    }else {
							
									$message="The minimum amount for the exchange is 0.0001 BCH";
						echo "<script type='text/javascript'>$(document).ready(function(){show_message('{$message}',3,6000); }); </script>";
						
							
						}
                }
                ?>
                

<div class="pc-message elven" id="msgw1">								
	        <div class="msg-type sm-success"></div>
	        <div class="content">Simple Text Message</div> 
	        <div class="decor middle"></div>
            <div class="decor left"></div>
            <div class="decor right"></div>
	    </div>           
                                             
                                            
                                        </div>
                                        <div class="clearfix"></div>
										<script type="text/javascript">	

function myFunction() {
  // Get the text field
  var copyText = document.getElementById('myInput').innerHTML;

     // Copy the text inside the text field
  navigator.clipboard.writeText(copyText);

  // Alert the copied text
  alert("Copied the address: " + copyText);
  
  
}
</script>

                                                                            </div>
                                    
                                </div>
                                
                                
                        </div>
                        
                        
                    </div>
                    <div class="decor middle"></div>
                    <div class="decor left"></div>
                    <div class="decor right"></div>
                </div>
            </div>
        </div>
    </div>


</section>

