<?php if(!defined('FastCore')){exit('Oops!');}

$opt['title'] = 'Withdrawal of funds';

if ($user['ban'] == 1){
    exit('Your account has been blocked for violating the rules');
}

/* Last deposit days */
$tlast = time()-60*60*24*4;
$tnow = time();
$last_in = $db->query('SELECT SUM(sum) FROM db_insert WHERE `add` >= '.$tlast.' AND `add` <= '.$tnow.' AND status = 1 AND `uid` = '.$uid.'')->fetchArray();
$lastInvest = round($last_in['SUM(sum)'],0); // Total amount deposit

if ($user['sum_in'] <= 199.9) {
if ($lastInvest <= 29.99) {
    $lastInsert = 1; // ок
} else {
    $lastInsert = 0;
}
} else {
    $lastInsert = 0;
}
/* End last deposit days */


# Activate account 
$accPay = 30; // start deposit
$accPay2 = 50; // repeat deposit

# Limit params
$dep = $user['sum_in'];
$sym = $_POST['sym'];
$sumManual = '9.99'; // We send large amounts for verification

if($dep >= $accPay2 && $dep <= 100000) {
    $sumlimit = $dep / 2;
    $sumlimit = floor($sumlimit);
    $sumlimit = round($sumlimit,2);
    $userHitr = 0; // заглушка
   } else {
    $userHitr = 1; // заглушка
    $sumlimit = 15;
   }

   $valid = $user['login'];
   $systemPay = 'tron';
   $currency = 'TRX';
   $minPay = 12;
   $maxPay = 5000;
   $maxPay2 = $sumlimit;
   $todayLimit = 24;

?>

<script>
var longtext = "<?=$user["login"]; ?>";
var smalltext = "<?=substr_replace($user['login'], "<span style='color: #dc3545;'>***</span>", -4, 9); ?>";
$(function() {
    $("#mytrx").html(smalltext);
    var done = false;
    $("#mytrx").click(function() {
        if (!done) {
            done = true;
            $(this).text(longtext);
        }
    });
});
</script>	


<?php

# Filter wallet
$wallet = new wallets();
$pWallet = 'tron_wallet';
$purse = $wallet->$pWallet($valid);

$sumUser = $user['money_p']; // -hold

# Form payment
$csrfCheck = $func->csrfVerify();
if(isset($_POST['pay']) && $csrfCheck == TRUE) {
$sum = filter_var($_POST['sum'], FILTER_VALIDATE_FLOAT);

if ($sum > 12) {
  $commision = '5.00';
} else {
  $commision = '10';
}
// fees amount
$com = $sum - ($sum * $commision /100);
$com = round($com,2);

# valit address
if(!($purse == $valid)) { 
  $errors[] = 'Purse '.$purse.' filled in incorrectly!'; 
}
# period last
if(empty($sym)) { 
$payments = $db->query("SELECT * FROM db_payout WHERE uid = '$uid'")->fetchArray();
if (!(time() >= $payments['add']+(3600*$todayLimit))) { 
  $errors[] = 'You have already ordered a payment for the last '.$todayLimit.' hour.'; 
}
# Limit payout min/max
if (!($sum  >= $minPay && $sum <= $maxPay)) { 
  $errors[] = 'Minimum payout amount is <b>'.$minPay.' {!VAL!}.</b><br>Maximum payout amount is <b>'.$maxPay.' {!VAL!}.</b>'; 
}
# Activate
if(!($user['sum_in'] >= $accPay)) {
  $errors[] = 'Make a deposit on '.$accPay.' {!VAL!}. After that, the payouts will be available.</b>'; 
}
# User balance
if(!($sum <= $sumUser)) {
  $errors[] = 'Error. Available balance for withdrawal '.$sumUser.' {!VAL!}.'; 
}
# no deposit was made for several days
if (!($lastInsert == 0)) {
  $errors[] = 'Make a deposit on '.$accPay.' {!VAL!}. After that, the payouts will be available.</b>'; 
}
# Limit payout min/max from deposit
if (!($sum >= $minPay && $sum <= $maxPay2)) { 
  $errors[] = '<b>Your daily limit:</b><br>Minimum payout amount is <b>'.$minPay.' {!VAL!}.</b><br>Maximum payout amount is <b>'.$maxPay2.' {!VAL!}.</b>'; 
}}

# Success
if (empty($errors)) {

  $da = time();
  $dd = $da + 60*60*24*15;
  $ppid = 1;

  # large manual payment
  if ($sum > $sumManual && $sym == false) {  
    # Updating user info    
    $db->query("INSERT INTO db_payout (uid, login, sum, `sys`, `add`, `del`, status) VALUES ('$uid', '$purse','$sum','$ppid','$da','$dd','1')");
    $db->query("UPDATE db_users SET sum_out = sum_out + '$sum', money_p = money_p - '$sum'  WHERE id = '$uid'");
    
    $db->query("UPDATE db_stats SET payments = payments + '$sum' WHERE id = '1'");
    
    $db->query("INSERT INTO db_history (uid, sum, login, `add`, `type`) VALUES ('$uid', '$sum', '$purse', '$da', '2')"); // history

      echo '<div class="alert alert-success">The request for payment has been sent, wait for the administrator to check!<br/><small> verification time usually takes from 10 minutes to 24 hours.</small></div>';
  } else {
    # successful payment API					
    $paykassa_api_id = $config->pka_id;
    $paykassa_api_password = $config->pka_pass;
    $paykassa_merchant_id = $config->pkm_id;
                               
    $test = false; // test mode false - off, true - on						
      $wallet = $purse;
      $comment = $user['id'];
  
      $paykassa = new PaykassaAPI($paykassa_api_id,$paykassa_api_password,$test);
  
      $params = [
          "merchant_id" => $paykassa_merchant_id, 
          "wallet" => [
              "address" => $wallet,
              "tag" => "",
          ],
          "amount" => $com,
          "system" => "TRON",
          "currency" => "TRX",
          "comment" => "My comment".$comment,
          "priority" => "hign", // low, medium, high
      ];
  
      $res = $paykassa->sendMoney(
          $params["merchant_id"],
          $params["wallet"],
          $params["amount"],
          $params["system"],
          $params["currency"],
          $params["comment"],
          $params["priority"]
      );
  
    if ($res['error']) {        // $res['error']
    //	echo $res['message'];   // $res['message']
      echo '<div class="alert alert-danger text-center">Make a deposit on '.$accPay.' {!VAL!}. After that, the payouts will be available.</div>';
    } else {  

      # Updating user info
      $db->query("INSERT INTO db_payout (uid, login, sum, `add`, `del`, status) VALUES ('$uid','$purse','$sum','$da','$dd','3')");
      $db->query("UPDATE db_users SET sum_out = sum_out + '$sum', money_p = money_p - '$sum'  WHERE id = '$uid'");

    $db->query("INSERT INTO db_history (uid, sum, login, `add`, `type`) VALUES ('$uid', '$sum', '$purse', '$da', '2')"); // history
      $db->query("UPDATE db_stats SET payments = payments + '$sum' WHERE id = '1'");

      echo '<div class="alert alert-success">Funds have been successfully transferred to your wallet</div>';
    } 
  }
}
else {
    # Errors
    echo '<div class="alert alert-danger">'.array_shift($errors).'</div>';
  }
}
?>



  

<div class="row">
<div class="col-3 p-2"></div>
<div class="col-lg-6 p-1">
<div class="card mt-1 mb-2">

<div class="p-2 p-lg-3">

<div class="header-top-dp">
             <h4>Make Withdrawal</h4>
         </div>
<div class="inf-t-send">
              <h5 style="font-size: 15px;margin: 0;padding:0;">TO</h5>
              
              <div class="list-for-c">
              <span class="notranslate mb-0 pb-0"><?=$user["login"]; ?></span>
              </div>
         </div>
    <form action="" method="POST">
<?php $func->csrf(); ?>


<div class="p-3 text-center"><label class="text-uppercase"><b>Withdraw amount:</b></label>



<div class="col-lg-6 col-md-8 m-auto">
<div class="input-group input-group-lg mb-2">
	<input type="text" class="form-control" placeholder="Payout amount" value="<?=round($sumUser,2); ?>" min="<?=$minPay;?>" max="<?=$maxPay;?>" name="sum">
	<span class="input-group-text">{!VAL!}</span>
</div>
</div>
<button class="btn btn-lg btn-danger text-uppercase" name="pay" type="submit">Withdrawal</button>
</div></form>
<div class="faq">
         
            <ul>
                <li>                 <h3>What is the minimum withdrawal?</h3>                 <p>The minimum withdrawal amount on our platform is 12 TRX (Tron) (We raised the minimum withdrawal due to the high fees of the payment gateway.).</p>             </li>             <li>                 <h3>How long does it take for the TRX withdrawal to be processed?</h3>                 <p>TRX withdrawals on our platform are usually instantaneous or take only a few seconds to be confirmed on the Tron blockchain.</p>             </li>             <li>                 <h3>Is there any fee associated with TRX withdrawals?</h3>                 <p>Yes, there is usually a small fee associated with a 1 TRX withdrawal.</p>             </li>
            </ul>
        </div>
</div>
</div>
</div>
</div>

