<?php 
$pay_methods = 
[
    array(
      'name' => 'BITCOIN',  
      's_name' => 'BTC'
    ),
    array(
      'name' => 'Gold',  
      'amount' => '50,000'
    ),
    array(
      'name' => 'Silver',  
      'amount' => '20,000'
    ),
    array(
      'name' => 'Bronze',  
      'amount' => '10,000'
    ),
    array(
      'name' => 'Flexi',  
      'amount' => '5,000'
    ),
    array(
      'name' => 'Easy',  
      'amount' => '1,000'
    )
];
//company details
$company_hype = "Your Excellency";
$sql50 ="select * from j_company"; //
$result50 = runSQL($sql50);
$data50 = mysqli_fetch_array($result50);
$company = $data50['j_name']; 
//$company_sms_unit_price = $data50['j_sms_charge']; 
$company_name = $data50['j_name']; 
$company_motto = $data50['j_motto']; 
$company_desc = $data50['j_desc']; 
$company_email = $data50['j_email']; 
$company_phone = $data50['j_phone']; 
$company_website = $data50['j_website']; 
$company_address= $data50['j_address']; 
$company_email_notify= $data50['j_email_notify']; 
$company_email_notify_pass= $data50['j_email_notify_pass'];
$company_referral_perc= $data50['j_referral_bonus'];
$company_referral_perc_2 = "0.25";
$company_cash_back_perc = "0.30";
$company_refund_fund_perc = "0.20";
$company_btc_address= $data50['j_btc_address'];
$company_eth_address= $data50['j_eth_address'];
$company_ltc_address= $data50['j_ltc_address'];
$company_reg_fee= $data50['j_reg_fee']; 
$company_bank_info = $data50['j_bank_info']; 

//
$fpk= $data50['j_fpk']; 
$fsk= $data50['j_fsk']; 
//
$ppk= $data50['j_ppk']; 
$psk= $data50['j_psk']; 
//
$sms_sender= $data50['j_sms_sender']; 
$sms_username= $data50['j_sms_username']; 
$sms_password= $data50['j_sms_password']; 
$sms_gateway= $data50['j_sms_gateway']; 
$watermark= $data50['j_watermark']; 
$acr= $data50['j_acr']; 
//

$facebook= $data50['j_facebook']; 
$twitter= $data50['j_twitter']; 
$instagram= $data50['j_instagram']; 
$youtube= $data50['j_youtube']; 
$whatsapp= $data50['j_whatsapp']; 
$telegram= $data50['j_telegram']; 



$android_app = "https://play.google.com/store/apps/details?id=thenewminds.com";
$ios_app = "";
//$android_app = "".$dir."";
$page_twitter_site="@thenewminds";
$page_twitter_creator="@thenewminds";
//
//$currency_in_use = "USD"; $currency_code_in_use = "$";
//$currency_in_use = "USD"; $currency_code_in_use = "&#36;";
//$currency_in_use = "NGN"; $currency_code_in_use = "&#x20a6;"; $currency_sort_in_use = "NG";
//
$currency_in_use = "NGN"; $currency_code_in_use = "&#x20a6;"; $currency_sort_in_use = "NG";

$m_text_color = "#da885b";
$m_text_color_hu = '#000000'; //highlight and underline
$m_address = "$company_address";
$m_phone = "$company_phone";
$m_email = "$company_email";
//
$currencies_array = array('NGN','GHS','KES','USD');
$gender_array = array('Male','Female','Company');
$profession_array = array('CEO','Founder','Sole-Proprietor','Manager','Staff','Other');
$music_genre_array = array('Blues','Classical','Country','Electronic','International','Jazz','Latin','Pop/Rock
','R&B','Rap','Reggae');
$packages = 
[
    array(
      'name' => 'Professional',  
      'amount' => '100,000'
    ),
    array(
      'name' => 'Gold',  
      'amount' => '50,000'
    ),
    array(
      'name' => 'Silver',  
      'amount' => '20,000'
    ),
    array(
      'name' => 'Bronze',  
      'amount' => '10,000'
    ),
    array(
      'name' => 'Flexi',  
      'amount' => '5,000'
    ),
    array(
      'name' => 'Easy',  
      'amount' => '1,000'
    )
];
$admin_referrer = 'finlig-user';
//
//<img src='../j_files/j_img/icons/bank-gtb.png' style='width:100px; height:auto;'/><br/> 
function bank_info ($currency){
    if($currency=="NGN"){
          $bank_info = "
          Bank: <b>Union Bank</b> 
          <br/>
          Account Number: <b>0113238045</b> 
          <br/>
          Account Name: <b></b> 
          ";
    }
    return $bank_info;
}





if(!empty($ppk) && empty($ipk)){
    $pay_method_array = 
    [
        array(
          'name' => 'Paystack',  
          'desc' => 'Card, USSD, Bank'
        ),
        
        array(
          'name' => 'Bank Transfer',  
          'desc' => 'Bank deposit/transfer'
        )
		/*
		array(
          'name' => 'Cash',  
          'desc' => 'Pay to '.$company.''
        )
        */
    ];
}


if(empty($ppk) && !empty($ipk)){
    $pay_method_array = 
    [
        array(
          'name' => 'IPayTotal',  
          'desc' => 'Card, USSD, Bank'
        )
        /*
        array(
          'name' => 'Bank Transfer',  
          'desc' => 'Mobile, USSD'
        )
        /*
		array(
          'name' => 'Cash',  
          'desc' => 'Pay to '.$company.''
        )
        */
    ];
}




//

function rave_vp($ref,$fsk){  //verify  pay 

    $sql4="SELECT * from j_pays WHERE j_deleted < 1 AND j_transact_id='".$ref."'"; // 
    $result4 = runSQL($sql4);
    $data4 = mysqli_fetch_array($result4);
    $currency = $data4['j_currency'];
    $amount = $data4['j_amount'];
    //
    $query = array(
        "SECKEY" => $fsk,
        "txref" => $ref 
    );
    

    $data_string = json_encode($query);
    //$ch = curl_init('https://ravesandboxapi.flutterwave.com/flwv3-pug/getpaidx/api/v2/verify'); //test
    $ch = curl_init('https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify');                                                                      
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                                              
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    $response = curl_exec($ch);

    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);

    curl_close($ch);

    $resp = json_decode($response, true);

    $paymentStatus = $resp['data']['status'];
    $chargeResponsecode = $resp['data']['chargecode'];
    $chargeAmount = $resp['data']['amount'];
    $chargeCurrency = $resp['data']['currency'];

    if (($chargeResponsecode == "00" || $chargeResponsecode == "0") && ($chargeAmount == $amount)  && ($chargeCurrency == $currency)) {
        return 1;
    } else {
        return 0;
    }
}




function paystack_vp($ref,$psk){  //verify  pay 
    //
    /*
    $sql4="SELECT * from j_pays WHERE j_deleted < 1 AND j_transact_id='".$ref."'"; // 
    $result4 = runSQL($sql4);
    $data4 = mysqli_fetch_array($result4);
    $currency = $data4['j_currency'];
    $amount = $data4['j_amount'];
    */
    //
    $result = array();
    //The parameter after verify/ is the transaction reference to be verified
    $url = 'https://api.paystack.co/transaction/verify/'.$ref.'';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt(
      $ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer '.$psk.'']
    );
    $request = curl_exec($ch);
    curl_close($ch);

    if ($request) {
        $result = json_decode($request, true);
        // print_r($result);
        if($result){
            if($result['data']){
                //something came in
                if($result['data']['status'] == 'success'){ return 1; }else{ return 0; }
            }else{ return 0; }
        }else{ return 0; }
    }else{ return 0; }
}



function check_psk_bal($psk){ 
    //get balance
    $url_here = "https://api.paystack.co/balance";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url_here);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/json";
    $headers[] = "Authorization: Bearer $psk";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //
    $status = $obj->status;
    $message = $obj->message;
    $currency = $obj->data[0]->currency;
    $balance = $obj->data[0]->balance;
    $balance = TWO_DEC($balance);
    return $balance;
}


//referral link
if(!isset($_SESSION['j_admin']) && !isset($_SESSION['j_admin'])){
    if(isset($_GET['u'])){
        $referrer_username  = RMC($_GET['u']);
        $sql50 ="select * from j_users where j_firstname !='' AND j_username='".$referrer_username."' AND j_blocked < 1 AND j_deleted < 1"; //
        $result50 = runSQL($sql50);
        $data50 = mysqli_fetch_array($result50);
        $referrer_id = $data50['j_id']; 
        if(!isset($_SESSION['u'])){
            if(!empty($referrer_id)){
                /*
                $sql4="SELECT * from j_pays WHERE 
                j_user_id='".$referrer_id."' AND j_kind='ACTIVATION' AND j_paid > 0 AND j_deleted < 1 order by j_id desc
                || j_user_id='".$referrer_id."' AND j_kind='ACTIVATION-A' AND j_paid > 0 AND j_deleted < 1 order by j_id desc
                || j_user_id='".$referrer_id."' AND j_kind='ACTIVATION-M' AND j_paid > 0 AND j_deleted < 1 order by j_id desc
                ";  
                $result4 = runSQL($sql4);
                $check = mysqli_num_rows($result4);
                if($check > 0){
                */
                    $_SESSION['u'] = RMC($referrer_id); //start session
                    $sql50 ="select * from j_users where j_id='".$_SESSION['u']."'"; //
                    $result50 = runSQL($sql50);
                    $data50 = mysqli_fetch_array($result50);
                    $r_firstname = $data50['j_firstname']; 
                    $r_lastname = $data50['j_lastname']; 
                    $r_name = trim("$r_firstname $r_lastname");
                    
                //}else{
                    //unset($_SESSION['u']);
                //}
                
            }else{
                unset($_SESSION['u']);
            }
        }else{
            $sql50 ="select * from j_users where j_id='".$_SESSION['u']."'"; //
            $result50 = runSQL($sql50);
            $data50 = mysqli_fetch_array($result50);
            $r_firstname = $data50['j_firstname']; 
            $r_lastname = $data50['j_lastname']; 
            $r_name = trim("$r_firstname $r_lastname"); 
        }
    }else{
        if(isset($_SESSION['u'])){
            $sql50 ="select * from j_users where j_id='".$_SESSION['u']."'"; //
            $result50 = runSQL($sql50);
            $data50 = mysqli_fetch_array($result50);
            $r_firstname = $data50['j_firstname']; 
            $r_lastname = $data50['j_lastname']; 
            $r_name = trim("$r_firstname $r_lastname");
        }
    }
}




function create_recipient($account_no, $account_name, $bank_code,$psk){
        
    $headers = ['Authorization: Bearer '.$psk,
                'Content-Type: application/json'
               ];
   
    $body = [
        'type' => 'nuban',
        'name' => $account_name,
        'account_number' => $account_no,
        'bank_code' => $bank_code,
        'currency' =>'NGN'
    ];
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://api.paystack.co/transferrecipient',
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_HEADER => false,
        CURLOPT_POSTFIELDS => json_encode($body)
    ));
    $resp = curl_exec($curl);

    if(curl_error($curl)){
        //echo 'error:' . curl_error($curl);
    }
    
    curl_close($curl);
    $result = json_decode($resp);
    //
    $status = $result->status;
    $recipient_code = $result->data->recipient_code;
    if ($status > 0) {
        
       }else {
		die("<div class='alert alert-danger'> Could not create recipient. Try another.</div>"); 
 	}
    
    //
    return $recipient_code;
}


function make_transfer($recipient_code, $reason, $amount,$psk){
    //$amount = $amount*100;
    $headers = ['Authorization: Bearer '.$psk,
                'Content-Type: application/json'
               ];
    $body = [
        'source' => 'balance',
        'reason' => $reason,
        'recipient' => $recipient_code,
        'amount' => $amount,
    ];
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://api.paystack.co/transfer',
        CURLOPT_POST => 1,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_HEADER => false,
        CURLOPT_POSTFIELDS => json_encode($body)
    ));
    $resp = curl_exec($curl);

    if(curl_error($curl)){
        //echo 'error:' . curl_error($curl); //touch here
    }
    
    curl_close($curl);

    $result = json_decode($resp);
    $status = $result->status;
     $transfer_code = $result->data->transfer_code;
    if ($status > 0) {
        
       }else {
		die("<div class='alert alert-danger'> Could not fetch transfer code. Try another.</div>"); 
 	}
    
   
    return $transfer_code;

}





function verify_transfer($transfer_code,$psk){
        
    $headers = ['Authorization: Bearer '.$psk];
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'https://api.paystack.co/transfer/'.$transfer_code,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_HEADER => false,
    ));
    $resp = curl_exec($curl);

    if(curl_error($curl)){
       //echo 'error:' . curl_error($curl);
    }

    curl_close($curl);

    $result = json_decode($resp);
    $currency = $result->data->recipient->currency;
    $amount = $result->data->amount;
    $account_name = $result->data->recipient->name;
    $account_no = $resp->data->recipient->details->account_number;
    $bank_name = $result->data->recipient->details->bank_name;
    //
    $status = $result->status;
    $message = $result->message;
    
    if ($status > 0) {
        
       }else {
		die("<div class='alert alert-danger'> Could not verify transfer code. Try another.</div>"); 
 	}
    
   
    return $status;

}

function get_cd($currency){  
	if($currency=="NGN"){ 
		$currency_in_use = "NGN"; $currency_code_in_use = "&#x20a6;"; $currency_sort_in_use = "NG";
	}elseif($currency=="USD"){ 
        $currency_in_use = "USD"; $currency_code_in_use = "&#36;"; $currency_sort_in_use = "US";  
	}elseif($currency=="GHS"){ 
		$currency_in_use = "GHS"; $currency_code_in_use = "GHS"; $currency_sort_in_use = "GH";  
	}else{
		$currency_in_use = $currency; $currency_code_in_use = $currency; $currency_sort_in_use = $currency;  
	}
	
	
    return array($currency_in_use,$currency_code_in_use,$currency_sort_in_use);
}



function send_sms($sender,$phone,$message,$schedule){
    global $sms_username;
    global $sms_password;
    $username = $sms_username;
    $password = $sms_password;
    $sender   = $sender;
    //$message  = urlencode($message);
    $message  = $message;
    $mobiles  = $phone;
    $api_url  = 'https://account.kudisms.net/api/';
    if(!empty($schedule)){
        $data = array('username'=>$username, 'password'=>$password, 'sender'=>$sender, 'message'=>$message, 'mobiles'=>$mobiles,'schedule'=>$schedule);
    }else{
        $data = array('username'=>$username, 'password'=>$password, 'sender'=>$sender, 'message'=>$message, 'mobiles'=>$mobiles);
    }
    //URL encode the message data
    $data = http_build_query($data);
    //Send the message
    $ch = curl_init(); 
    // Initialize a cURL connection
    curl_setopt($ch,CURLOPT_URL, $api_url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    $result = json_decode($result);
    //print_r($result);
    if(isset($result->status) && strtoupper($result->status) == 'OK'){
        $status = 1; $price = $result->price;
        //echo 'Message sent at N'.$result->price;
        return array($status,$price); 
    }else if(isset($result->error)){
        $status = $result->error; $price = 0;
        return array($status,$price);
        //echo 'Message failed -error: '.$result->error;
    }else{ 
        $status = 'Unable to process request'; $price = 0;
        return array($status,$price);
        // Could not determine the message response.
    }
   return 1; 
}






function access_token($url,$client_id,$client_secret,$audience,$grant_type){
$url ='https://auth.reloadly.com/oauth/token';
$data = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'audience' => $audience,
'grant_type' => $grant_type,
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER,[
'Content-Type: application/json'
]);
$response = curl_exec($curl);
curl_close($curl);
$responseData = json_decode($response);
$access_token = $responseData->access_token;
$expires_in = $responseData->expires_in;
$scope = $responseData->scope;
return array($access_token,$expires_in,$scope);
}
//end


function account_balance($url,$access_token){ //get-balance
    $url = 'https://topups.reloadly.com/accounts/balance';    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    $balance = $obj->balance;
    $currencyCode = $obj->currencyCode;
    $currencyName = $obj->currencyName;
    $updatedAt = $obj->updatedAt;
    return array($balance,$currencyCode,$currencyName,$updatedAt);
}





function countries($url,$access_token){
    $url="https://topups.reloadly.com/countries";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //echo "<pre>";
    //print_r($obj);
    //$balance = $obj->balance;
    return $obj;
}




function countries_by_iso($url,$country_code,$access_token){
    $url="https://topups.reloadly.com/countries/$country_code";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //echo "<pre>";
    //print_r($obj);
    //$balance = $obj->balance;
    return $obj;
}




function operators($url,$access_token){
    $url="https://topups.reloadly.com/operators?page=1&size=3&suggestedAmounts=true&suggestedAmountsMap=true&includeBundles=true";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //echo "<pre>";
    //print_r($obj);
    //$balance = $obj->balance;
    return $obj;
}

function operators_by_phone($phone,$country_code,$access_token){ //operators by id, phone,iso
    $url="https://topups.reloadly.com/operators/auto-detect/phone/$phone/countries/$country_code?&includeBundles=true";
    //$url="https://topups.reloadly.com/operators/auto-detect/phone/$phone?&includeBundles=false";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //echo "<pre>";
    //print_r($obj);
    //$balance = $obj->balance;
    return $obj;
}



function operators_by_iso($country_code,$access_token){ //operators by id, phone,iso
    $url="https://topups.reloadly.com/operators/countries/$country_code";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //
    $headers = array();
    $headers[] = "Accept: application/com.reloadly.topups-v1+json";
    $headers[] = "Authorization: Bearer $access_token";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    //
    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
     }
    curl_close ($ch);
    //echo $result;
    $obj = json_decode($result);
    //echo "<pre>";
    //print_r($obj);
    //$balance = $obj->balance;
    return $obj;
}

function refund_vtu($ref){ 
    global $company; 
    global $company_email; 
    global $acr; 
    global $company_motto; 
    global $CurrentDate; 
    $sql4="SELECT * from j_pays WHERE j_kind='AIRTIME' AND j_transact_id='".$ref."' AND j_deleted < 1 order by j_id desc";  
    $result4 = runSQL($sql4);
    $data4 = mysqli_fetch_array($result4);
    $ref = $data4['j_transact_id']; 
    $currency = $data4['j_currency']; 
    $amount = $data4['j_amount']; 
    $user_id = $data4['j_user_id']; 
    $service = $data4['j_kind']; 
    $paid = $data4['j_paid']; 
    $status = $data4['j_status'];
    //user profile
    $sql25="SELECT * from j_users WHERE 
    j_id='".$user_id."'"; //  
    $result25 = runSQL($sql25);
    $data25 = mysqli_fetch_array($result25);
    $wallet = $data25['j_wallet'];
    $id = $data25['j_id'];
    $username = $data25['j_username'];
    $email = $data25['j_email'];
    $phone = $data25['j_phone'];
    $firstname = $data25['j_firstname'];
    $lastname = $data25['j_lastname'];
    $name = "$firstname $lastname"; $name = trim($name);
    //
    if($paid<1){
        return array('01','Payment was unsuccessful');
    }else{
        if($status>0){
            return array('02','Payment was successful and service has been delivered');
        }else{
            //check if no refund on the case to avoid multiple refund
            $sql4="SELECT * from j_pays WHERE j_kind='REFUND' AND j_refund_id='".$ref."' AND j_deleted < 1 order by j_id desc";  
            $result4 = runSQL($sql4);
            $data4 = mysqli_fetch_array($result4);
            $refund_ref = $data4['j_refund_id'];
            if($refund_ref==$ref){
                return array('03','Already refunded'); //already refunded
            }else{
                //verify the ref
                
                //refund now
                $timex = time();
                $bal = TWO_DEC($wallet+$amount);
                $sql4="SELECT count(*) as sum from j_pays"; //check 
                $result4 = runSQL($sql4);
                $data4 = mysqli_fetch_array($result4);
                $sum4 = $data4['sum']; $sum4 = $sum4+1;
                $transact_id = "$acr-$sum4-$timex";
                //record transaction as unpaid
                $paid = 1; 
                $type = "credit";
                $kind = "REFUND";
                $reason = "Refund on $service purchase";
                $gateway = "Wallet"; //Paystack Rave
                $sql = "INSERT INTO j_pays 
                (j_refund_id,j_transact_id,j_user_id,j_currency,j_amount,j_bal,j_type,j_kind,j_gateway,j_desc,j_paid,j_date)
                VALUES
                ('".$ref."','".$transact_id."','".$user_id."','".$currency_in_use."','".$amount."','".$bal."','".$type."','".$kind."','".$gateway."','".$reason."','".$paid."','".$CurrentDate."')
                ";
                $result = runSQL($sql);
                if(!$result){
                   die("
                    <div class='alert alert-danger'> Error. Code 104. Try again.</div>
                    "
                    ); 
                }
                //add up the coins
                $sql="UPDATE j_users SET j_wallet='".$bal."' WHERE j_id='".$id."' AND j_deleted < 1";  
                $result = runSQL($sql);
                //send a mail for user
                $u_email = $email;
                $u_subject ="REFUND";
                $u_subject_n ="REFUND";
                $u_message ="<p>Dear <b>$name</b>;</p> 
                <p>You have received refund on transaction with reference ID: <b>$ref</b>
                <br/><br/>
                <b>Transaction Details</b>
                <br/>
                Amount: <b>".num_format($amount)." $currency</b><br/>
                Service : <b>$service</b><br/>
                Reference ID : <b>$transact_id</b><br/>
                <br/>
                Thank you for choosing <b>$company</b>
                <br/>
                <em>$company_motto</em>
                <br/>
                </p>";
                //require("../mail.php");
                //send notify
                send_notify("",$id,$u_subject_n,$u_message);
                //
                return array('1','Refund was successful');
                //return ("$ref - $transact_id -$curency -$amount- $user_id- $kind-$paid-$status");
            }            
        }
    }
}









function getIPAddress() {  
    //whether ip is from the share internet  
     if(!empty($_SERVER['HTTP_CLIENT_IP'])) {  
                $ip = $_SERVER['HTTP_CLIENT_IP'];  
        }  
    //whether ip is from the proxy  
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
     }  
//whether ip is from the remote address  
    else{  
             $ip = $_SERVER['REMOTE_ADDR'];  
     }  
     return $ip;  
}  

//info for AIRTIME AND DATA
$c_client_id = '';
$c_client_secret = '';
$c_audience = 'https://topups.reloadly.com';
$c_grant_type = 'client_credentials';
//
$company_TRADING_perc = 1;
$company_TRADING_fee = 0;

function crypto_usd($from,$to){
	if($from=="BTC"){
		$data = file_get_contents("https://blockchain.info/tobtc?currency=$to&value=1"); $data = trim($data);
		$crypto_usd = 1/$data;
		return $crypto_usd;
	}elseif($from=="ETH"){
		$data = file_get_contents("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=ethereum");
		$data = json_decode($data, TRUE);
		$crypto_usd = $data[0]['current_price'];
		//print_r($data);
		return $crypto_usd;
	}else{
		//use cryptocompare; its free but 6000 request per day or month
		$data = file_get_contents("https://min-api.cryptocompare.com/data/price?fsym=$from&tsyms=$to");
		$data = json_decode($data, TRUE);
		//print_r($data);
		$rate = $data['USD'];
		return $rate;

	}
	//end cryptocompare
	
	//blockchain
	//https://www.blockchain.com/api/exchange_rates_api  for only bitcoin and free for life
	//end blockchain

	//advfn somehow unlimited
	/*
	$data = file_get_contents("https://www.advfn.com/common/cryptocurrency/converter/api/getConversion?from=BTC&to=USD&amount=1");
	$data = json_decode($data, TRUE);
	$amount = $data['amount'];
	//$chart_img = $data->chart->image;
	$rate_single = $data['conversion_unformatted'];
	*/
	//https://www.advfn.com/cryptocurrency/converter/LTC/USD
	//https://www.advfn.com/common/cryptocurrency/converter/api/getConversion?from=BTC&to=USD&amount=1
	//end advfn
	
}


function usd_ngn($from,$to){
	$sql255="SELECT * from j_exchange_rates WHERE 
	j_deleted < 1 AND j_from='".$from."' AND j_to='".$to."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$rate = $data25['j_amount'];
	return $rate;	
}

function usd_ngn_info($from,$to){
	$sql255="SELECT * from j_exchange_rates WHERE 
	j_deleted < 1 AND j_from='".$from."' AND j_to='".$to."'
	|| j_deleted < 1 AND j_from='".$from."' AND j_to='".$to."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$min_usd = $data25['j_min'];
	$max_usd = $data25['j_max'];
	$processing_fee_usd = $data25['j_transfer_fee'];
	$profit_usd = $data25['j_profit'];
	$profit_perc_usd = $data25['j_profit_perc'];
	return array($min_usd,$max_usd,$processing_fee_usd,$profit_usd,$profit_perc_usd);	
}


function referral_bonus($user_id,$referrer_id,$ref,$r_bonus,$currency_in_use,$currency_code_in_use){
	global $company_hype;
	global $company;
	global $company_referral_perc;
	global $CurrentDate;
	global $dir;
	global $acr;
	
	
	//get referrer info using the id
	$sql255="SELECT j_firstname,j_lastname from j_users WHERE 
	j_id='".$user_id."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$u_firstname = $data25['j_firstname'];
	$u_lastname = $data25['j_lastname'];
	$u_name = trim("$u_firstname $u_lastname");
	
	//get referrer info using the id
	$sql255="SELECT * from j_users WHERE 
	j_id='".$referrer_id."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$r_id = $data25['j_id'];
	$r_email = $data25['j_email'];
	$r_phone = $data25['j_phone'];
	$r_firstname = $data25['j_firstname'];
	$r_lastname = $data25['j_lastname'];
	$r_wallet = $data25['j_wallet']; 
	$r_wallet_usd = $data25['j_wallet_usd']; 
	$r_wallet_btc = $data25['j_wallet_btc']; 
	$r_wallet_eth = $data25['j_wallet_eth']; 
	$r_wallet_ltc = $data25['j_wallet_ltc']; 
	
	if($currency_in_use=="NGN"){ $r_wallet = $r_wallet; $wallet_db = "j_wallet";}
	//if($currency_in_use=="USD"){ $r_wallet = $r_wallet_usd; $wallet_db = "j_wallet_usd"; }
	if($currency_in_use=="USD"){ $r_wallet = $r_wallet; $wallet_db = "j_wallet"; }
	
	if($currency_in_use=="BTC"){  $r_wallet = $r_wallet_btc; $wallet_db = "j_wallet_btc"; }
	if($currency_in_use=="ETH"){ $r_wallet = $r_wallet_eth; $wallet_db = "j_wallet_eth"; }
	if($currency_in_use=="LTC"){ $r_wallet = $r_wallet_ltc; $wallet_db = "j_wallet_ltc"; }
	
	$r_wallet = $r_wallet; $wallet_db = "j_wallet"; //comment this if multiple currency
	
	$r_bal = $r_wallet+$r_bonus; 
	//$r_bal = TWO_DEC($r_bal); 
	$r_bal = TWO_DEC($r_bal);
	
	$r_name = trim("$r_firstname $r_lastname");
	if(!empty($r_id)){
		//START A NEW TRANSACTION AND UPDATE USER ACCOUNT
		$timex = time();
		$amount = $r_bonus;
		$bal = $r_wallet;
		//
		$sql4="SELECT count(*) as sum from j_pays"; //check 
		$result4 = runSQL($sql4);
		$data4 = mysqli_fetch_array($result4);
		$sum4 = $data4['sum']; $sum4 = $sum4+1;
		$transact_id_n = "$acr-$sum4-$timex";
		//record transaction
		$ip = getIPAddress();
		$type = "credit";
		$kind = "REFERRAL-BONUS";
		$reason = "Referral Bonus on $u_name ($ref)";
		$gateway = "Wallet";
		$paid = 0;
		//insert 
		$sql = "INSERT INTO j_pays 
		(j_transact_id,j_ref,j_user_id,j_currency,j_amount,j_bal,j_type,j_kind,j_desc,j_gateway,j_paid,j_date,j_ip)
		VALUES
		('".$transact_id_n."','".$ref."','".$referrer_id."','".$currency_code_in_use."','".$amount."','".$r_wallet."','".$type."','".$kind."','".$reason."','".$gateway."','".$paid."','".$CurrentDate."','".$ip."')
		";
		$result = runSQL($sql);
		if(!$result){
		   die("
			<div class='alert alert-danger'> Error. Code 104. Try again.</div>
			"
			); 
		}
		//
		//$r_bal = TWO_DEC_CRYPTO($r_bal,$currency_code_in_use);
		//
		//update record
		$sql = "UPDATE j_pays SET
		j_paid = '1', j_disburse = '1',j_bal ='".$r_bal."'
		WHERE j_transact_id='".$transact_id_n."' AND j_deleted < 1
		";
		$result = runSQL($sql);
		if(!$result){
			die("<div class='alert alert-danger'> Error. Try again.</div>
			");
		}
		//credit user account
		$sql = "UPDATE j_users SET
		$wallet_db ='".$r_bal."'
		WHERE j_id='".$referrer_id."'";
		$result = runSQL($sql);
		if(!$result){
			die("Error. Code 103.");
		}
		//
		//send a mail for referrer
		$u_email = $r_email;
		$u_subject ="REFERRAL BONUS";
		$u_subject_n ="REFERRAL BONUS";
		$u_message ="<p>Hello <b>$r_name</b>;</p> <p>You have earned ".amount_w_c($r_bonus,$currency_in_use)." for referring <b>$u_name</b> to <b>$company</b>.
		<br/>
		Refer more and earn up to <b>$company_referral_perc%</b> on your referrals.
		<br/><br/>
		<a href='".$dir."wallet/' class='btn btn-md btn-primary'> Account Balance </a>
		<br/><br/>
		Thank you for choosing <b>$company</b>.
		</p>";
		//require("../mail.php");
		//send notify
		send_notify("",$r_id,$u_subject_n,$u_message);
	} //user id invalid
}








function transfer_credit($re_id,$sender_id,$ref,$amount,$currency_in_use,$currency_code_in_use){
	
	global $company_hype;
	global $company;
	global $company_referral_perc;
	global $CurrentDate;
	global $dir;
	global $acr;
	
	//die("$user_id-$ref-$type-$kind-$reason-$amount-");
	//get referrer info using the id
	$sql255="SELECT * from j_users WHERE 
	j_id='".$sender_id."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$u_username = $data25['j_username'];
	$u_email = $data25['j_email'];
	$u_firstname = $data25['j_firstname'];
	$u_lastname = $data25['j_lastname'];
	$u_name = trim("$u_firstname $u_lastname");
	
	//get my info using the id
	$sql255="SELECT * from j_users WHERE 
	j_id='".$re_id."'"; //  
	$result255 = runSQL($sql255);
	$data25 = mysqli_fetch_array($result255);
	$r_id = $data25['j_id'];
	$r_email = $data25['j_email'];
	$r_phone = $data25['j_phone'];
	$r_firstname = $data25['j_firstname'];
	$r_lastname = $data25['j_lastname'];
	
	$r_wallet = $data25['j_wallet']; 
	$r_wallet_usd = $data25['j_wallet_usd']; 
	$r_wallet_btc = $data25['j_wallet_btc']; 
	$r_wallet_eth = $data25['j_wallet_eth']; 
	$r_wallet_ltc = $data25['j_wallet_ltc']; 
	
	if($currency_in_use=="NGN"){ $r_wallet = $r_wallet; $wallet_db = "j_wallet";}
	if($currency_in_use=="USD"){ $r_wallet = $r_wallet_usd; $wallet_db = "j_wallet_usd"; }
	if($currency_in_use=="BTC"){  $r_wallet = $r_wallet_btc; $wallet_db = "j_wallet_btc"; }
	if($currency_in_use=="ETH"){ $r_wallet = $r_wallet_eth; $wallet_db = "j_wallet_eth"; }
	if($currency_in_use=="LTC"){ $r_wallet = $r_wallet_ltc; $wallet_db = "j_wallet_ltc"; }
	
	$r_bal = $r_wallet+$amount; 
	//$r_bal = TWO_DEC($r_bal); 
	$r_bal = TWO_DEC_CRYPTO($r_bal,$currency_in_use);
	//
	$r_name = trim("$r_firstname $r_lastname");
	
	if(!empty($r_id)){
		//START A NEW TRANSACTION AND UPDATE USER ACCOUNT
		$timex = time();
		$amount = $amount;
		$bal = $r_wallet;
		//
		$sql4="SELECT count(*) as sum from j_pays"; //check 
		$result4 = runSQL($sql4);
		$data4 = mysqli_fetch_array($result4);
		$sum4 = $data4['sum']; $sum4 = $sum4+1;
		$transact_id_n = "$acr-$sum4-$timex";
		//record transaction
		$ip = getIPAddress();
		$type = "credit";
		$kind = "TRANSFER";
		$reason = "Credit alert from $u_name ($ref)";
		$gateway = "Wallet";
		$paid = 0;
		//insert 
		$sql = "INSERT INTO j_pays 
		(j_transact_id,j_ref,j_user_id,j_sender_id,j_currency,j_amount,j_bal,j_type,j_kind,j_desc,j_gateway,j_paid,j_date,j_ip)
		VALUES
		('".$transact_id_n."','".$ref."','".$re_id."','".$sender_id."','".$currency_in_use."','".$amount."','".$bal."','".$type."','".$kind."','".$reason."','".$gateway."','".$paid."','".$CurrentDate."','".$ip."')
		";
		$result = runSQL($sql);
		if(!$result){
		   die("
			<div class='alert alert-danger'> Error. Code 104. Try again.</div>
			"
			); 
		}
		//
		$bal = TWO_DEC_CRYPTO($r_bal,$currency_in_use);
		//
		//update record
		$sql = "UPDATE j_pays SET
		j_paid = '1', j_disburse = '1',j_bal ='".$bal."'
		WHERE j_transact_id='".$transact_id_n."' AND j_deleted < 1
		";
		$result = runSQL($sql);
		if(!$result){
			die("<div class='alert alert-danger'> Error. Try again.</div>
			");
		}
		//credit user account
		$sql = "UPDATE j_users SET
		$wallet_db ='".$bal."'
		WHERE j_id='".$re_id."'";
		$result = runSQL($sql);
		if(!$result){
			die("Error. Code 103.");
		}
		//
		
		//send a mail for user
		$u_email = $r_email;
		$u_subject ="CREDIT - $transact_id_n";
		$u_subject_m ="CREDIT ALERT";
		$u_message ="$company_hype <b>$r_name</b>; <br/>
		You have successfully received <b>".amount_w_c($amount,$currency_in_use)."</b> from <b>$u_name</b> (<b>$u_username</b>.
		<br/><br/>
		Remaining Balance: <b>".amount_w_c($bal,$currency_in_use)."</b> 
		<br/><br/>
		Payment Reference: <b>$transact_id_n</b>
		<br/><br/>
		Thank you for choosing $company
		";
		//require("../mail.php");	
		//send notify
		send_notify("",$re_id,$u_subject_m,$u_message);
		
	} //user id invalid
}


function company_charges($module,$amount){ 
	if($module=='withdraw'){ //in usd
		$min = 2.5; 
		$max = 10000;
		$processing_fee = 0.6;
		$processing_fee_perc = 0;
		$profit = 0;
		$profit_perc = 0.1;
		//
		$charge = array($min,$max,$processing_fee,$processing_fee_perc,$profit,$profit_perc);
	}
	if($module=='transfer'){ //in usd
		$min = 0; 
		$max = 100000;
		$processing_fee = 0;
		$processing_fee_perc = 0;
		$profit = 0.2;
		$profit_perc = 0;
		//
		$charge = array($min,$max,$processing_fee,$processing_fee_perc,$profit,$profit_perc);
	}
	if($module=='buy_crypto'){ //in usd
		$min = 10; 
		$max = 1000000;
		$processing_fee = 1;
		$processing_fee_perc = 0.5;
		$profit = 2;
		$profit_perc = 0.1;
		//
		$charge = array($min,$max,$processing_fee,$processing_fee_perc,$profit,$profit_perc);
	}
	if($module=='sell_crypto'){ //in usd
		if($amount <= 1000){
			$min = 10; 
			$max = 1000000;
			$processing_fee = 0;
			$processing_fee_perc = 4;
			$profit = 0;
			$profit_perc = 0;
		
		}elseif($amount > 1000 && $amount <= 20000){
			$min = 10; 
			$max = 1000000;
			$processing_fee = 0;
			$processing_fee_perc = 3;
			$profit = 0;
			$profit_perc = 0;
		
		}elseif($amount > 20000){
			$min = 10; 
			$max = 1000000;
			$processing_fee = 0;
			$processing_fee_perc = 2;
			$profit = 0;
			$profit_perc = 0;
		}
		//
		$charge = array($min,$max,$processing_fee,$processing_fee_perc,$profit,$profit_perc);
	}
	return $charge;
}







$TRADING_array = array(
	array("7 Days","7","Days","2","0",100,19999,'G-Basic'),
	array("30 Days","30","Days","5","0",20000,10000000,'G-Premium')
);

$company_highest_inv_perc = "5";	
/*
function rave_transfer_money($acr,$p_new_reference,$p_desc,$p_amount,$p_currency,$p_currency_debit,$p_bank_code,$p_account_no,$p_account_name, $p_branch_code,$fsk){  //verify  transfer 
    //make the transfer
    if($p_currency=="NGN"){
    $post = [
        'seckey' => $fsk,
        'account_bank' => $p_bank_code,
        'account_number' => $p_account_no,
        'amount' => $p_amount,
        'currency' => $p_currency,
        'narration' => $p_desc,
        'reference' => $p_new_reference,
        'beneficiary_name' => $p_account_name,
        'debit_currency' => $p_currency_debit
     ];
     }elseif($p_currency=="GHS"){
         $post = [  
        'seckey' => $fsk,
        'account_bank' => $p_bank_code,
        'account_number' => $p_account_no,
        'destination_branch_code' => $p_branch_code,
        'amount' => $p_amount,
        'currency' => $p_currency,
        'narration' => $p_desc,
        'reference' => $p_new_reference,
        'beneficiary_name' => $p_account_name,
        'debit_currency' => $p_currency_debit   
     ];
    }else{
        $post = [
        'seckey' => $fsk,
        'account_bank' => $p_bank_code,
        'account_number' => $p_account_no,
        'amount' => $p_amount,
        'currency' => $p_currency,
        'narration' => $p_desc,
        'reference' => $p_new_reference,
        'beneficiary_name' => $p_account_name,
        'debit_currency' => $p_currency_debit
     ];   
        
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.ravepay.co/v2/gpx/transfers/create");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    $headers = array();
    $headers[] = "Accept: application/json";
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        //echo 'Error:' . curl_error($ch);
    }
    curl_close ($ch);
    //$result;
    $result = json_decode($result);
    $t_status_1 = $result->status;
    $t_status = $result->data->status;
    //$responsecode = $result->data->data->responsecode;
    if(strtolower($t_status)=="new" || strtolower($t_status_1)=="success"){
        return 1;
    }else{ 
     return 0;
    }
}
*/
 
function t_status($data,$pay_id) { //display
	global $company;
	global $CurrentDate;
	global $dir;
	global $acr;
	//get end date
	$sql50 ="select j_end_date from j_pays where j_id='".$pay_id."'"; //
	$result50 = runSQL($sql50);
	$data50 = mysqli_fetch_array($result50);
	$end_date = $data50['j_end_date']; 
	if($data=="0"){ $status="<b class='text-danger'>Unpaid</b>"; } 
	if($data=="1"){ $status="<b class='text-warning'>Waiting for confirmation</b>"; } 
	if($data=="2"){ $status="<b class='text-primary'>Approved</b>"; } 
	if($data=="3"){ $status="<b class='text-danger'>Cancelled</b>"; } 
	if($data=="4"){ 
		$status="<b class='text-success'>Approved &amp; Credited</b>";
	} 
	//if($data=="5"){ $status="<b class='text-success'>Expired</b>"; } 
	return $status;
}
 

function t_status2($data,$paid,$disburse,$pay_id) { //display
	global $company;
	global $CurrentDate;
	global $dir;
	global $acr;
	//get end date
	$sql50 ="select j_end_date from j_pays where j_id='".$pay_id."'"; //
	$result50 = runSQL($sql50);
	$data50 = mysqli_fetch_array($result50);
	$end_date = $data50['j_end_date']; 
	if($paid < 1){
		if($data=="0"){ $status="<b class='text-danger'>Waiting for confirmation</b>"; } 
		if($data=="1"){ $status="<b class='text-warning'>Waiting for confirmation</b>"; } 
		if($data=="2"){ $status="<b class='text-danger'>Rejected</b>"; } 
		if($data=="3"){ 
			$status="<b class='text-success'>Approved &amp; Credited</b>";
		} 
	}else{
		if($disburse < 1){
			$status="<b class='text-warning'>Paid, waiting for credit</b>";
			 
		}else{
			$status="<b class='text-success'>Credited</b>";
		}
		
	}
	//if($data=="5"){ $status="<b class='text-success'>Expired</b>"; } 
	return $status;
}


?>