<?php
    include("../config.php");
    if(isset($_POST['bank_code'])){
        $ac_number = $_POST['account_num'];
        $ac_code = $_POST['bank_code'];
        $act_names = $_POST['account_name'];
        $code = $_POST['cm'];
        $amount = $_POST['amount'];
        
        
        $sels = $conn->query("SELECT * FROM `bank_details` WHERE `code`='$code'");
        $row_sels = mysqli_fetch_array($sels);
        $r_codes = $row_sels['r_code'];
        
        $av_bal_ref = $conn->query("SELECT * FROM `referral` WHERE `code`='$code'");
        $c_rvc = mysqli_num_rows($av_bal_ref);
        
        if(mysqli_num_rows($av_bal_ref) >= 1){
            $sql_porc = $conn->query("SELECT SUM(`amount`) AS `amt` FROM `referral` WHERE `code`='$code'");
            $r_sc = mysqli_fetch_array($sql_porc);
            $av_bal_ref = (int)$r_sc['amt'];
        }else{
            $av_bal_ref = 0;
        }
        
        if($amount > $av_bal_ref){
            echo '<div class="alert alert-danger" style="font-weight: bold; margin-top: 10px;"><em class="icon ni ni-shield-star-fill"></em>&nbsp;
            Insufficient Account Balance
            </div>';
        }else if($amount < 1000){
            echo '<div class="alert alert-danger" style="font-weight: bold; margin-top: 10px;"><em class="icon ni ni-shield-star-fill"></em>&nbsp;
            Minimum Amount to withdraw is 1000 NGN
            </div>';
        }else{
            if($r_codes == ''){
                getcode($code, $ac_number, $ac_code, $act_names, $conn, $av_bal_ref, $amount);
            }else{
                
                initiatetransfer($conn, $av_bal_ref, $amount, $r_codes, $code);
            }
        }
        
    }
  
  
  function getcode($code, $ac_num, $bank_code, $ac_name, $conn, $av_bal_ref, $amount){
      
      $url = "https://api.paystack.co/transferrecipient";
      $fields = [
        'type' => "nuban",
        'name' => $ac_name,
        'account_number' => $ac_num,
        'bank_code' => $bank_code,
        'currency' => "NGN"
      ];
      $fields_string = http_build_query($fields);
      //open connection
      $ch = curl_init();
      
      //set the url, number of POST vars, POST data
      curl_setopt($ch,CURLOPT_URL, $url);
      curl_setopt($ch,CURLOPT_POST, true);
      curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer sk_live_d3ab9a7f934cb3c400ca40ac602f72255f8655eb",
        "Cache-Control: no-cache",
      ));
      
      //So that curl_exec returns the contents of the cURL; rather than echoing it
      curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
      
      //execute post
        $response = curl_exec($ch);
        
        $err = curl_error($ch);
        curl_close($ch);
        if ($err) {
            echo "cURL Error #:" . $err;
        }else{
            $result = json_decode($response);
            $verify = $result->status;
        }
    
        if($verify){
            $rec_code = $result->data->recipient_code;
            $qs = $conn->query("UPDATE `bank_details` SET `r_code`='$rec_code' WHERE `code`='$code'");
            if($qs == true){
                initiatetransfer($conn, $av_bal_ref, $amount, $rec_code, $code);
            }else{
                echo 'Try Again';
            }
        }

      
  }
  
  
  function initiatetransfer($conn, $bal, $amount, $rec_code, $code){
      $amountc = $amount.'00';
      $amountb = (int)$amountc;
      //$amount = rawurlencode($amount);
      $url = "https://api.paystack.co/transfer";
      $fields = [
        'source' => "balance",
        'amount' => $amountb,
        'recipient' => $rec_code,
        'reason' => "Eagle Winks Payment"
      ];
      $fields_string = http_build_query($fields);
      //open connection
      $ch = curl_init();
      
      //set the url, number of POST vars, POST data
      curl_setopt($ch,CURLOPT_URL, $url);
      curl_setopt($ch,CURLOPT_POST, true);
      curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer sk_live_d3ab9a7f934cb3c400ca40ac602f72255f8655eb",
        "Cache-Control: no-cache",
      ));
      
      //So that curl_exec returns the contents of the cURL; rather than echoing it
      curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
      
      //execute post
      $response = curl_exec($ch);
        
        $err = curl_error($ch);
        curl_close($ch);
        if ($err) {
            echo "cURL Error #:" . $err;
        }else{
            $result = json_decode($response);
            $verify = $result->status;
        }
    
        if($verify){
            $reference = $result->data->reference;
            $date = $result->data->updatedAt;
            $status = $result->data->status;
            $tbal = $bal - $amount;
            $qs = $conn->query("INSERT INTO `user_withdraw`(`id`, `code`, `amount`, `date`, `ref_id`, `status`) VALUES (NULL,'$code','$amount','$date','$reference','$status')");
            if($qs == true){
                $conn->query("UPDATE `referral` SET `amount`='$tbal' WHERE `code`='$code'");
                echo '<div class="alert alert-success" style="font-weight: bold; margin-top: 10px;">
                <em class="icon ni ni-check-circle-fill"></em>
                Withdrawal was Successful. Your account will be credited within 10mins - 4hours
                </div>';
            }else{
                echo 'Try Again';
            }
        }else{
            echo '<div class="alert alert-danger" style="font-weight: bold; margin-top: 10px;"><em class="icon ni ni-shield-star-fill"></em>Transaction failed. Please Try Again</div>';
        }
  }
?>