<?php
  

 header('Content-Type : application/json');
  
    require_once('../../db.php');


	// API parameter
    
	if(isset($_REQUEST['apikey']) && isset($_REQUEST['service']) && isset($_REQUEST['meterNo']) && isset($_REQUEST['metertype']) && isset($_REQUEST['amount']) && isset($_REQUEST['ref']) ){
	
	$apikey = $_REQUEST['apikey'];
	$serviceID = $_REQUEST['service'];
	$metertype = $_REQUEST['metertype'];
	$meterNo = $_REQUEST['meterNo'];
	$ref = $_REQUEST['ref'];
	$network = $_REQUEST['service'];
	$xamount = $_REQUEST['amount'];
	$auth = "paid";
	
	
	$apikey = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $apikey);
	$serviceID = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $serviceID);
	$metertype  = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $metertype);
	$meterNo = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $meterNo);
	$ref = str_replace( array( '/', '(', ')',   'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $ref);
	$network = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $network);
	$amount = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $xamount);
	

    $variation_code = $metertype;
	
    $action = substr(str_shuffle("0123456789678901"), 0, 8);
	$del = substr(str_shuffle("0123456789678901"), 0, 7);
	$channel = "API";
	$view = "View";
	date_default_timezone_set('Africa/Lagos');
    $dateTime = date('Y-m-d h:i A');
	
	// check if the account is valid
	

	
	if($param){
	    
	    response(107,"BAD REQUEST");} else{
	
	$retr = "SELECT * FROM users WHERE apikey='$apikey' ";
	
	$exe = mysqli_query($conn,$retr);
	$rob = mysqli_fetch_array($exe);
	
	$user = $rob['apikey'];
	$aut = $rob['level'];
	
	$arr = array("$apikey","$auth");
	
	$pair = array("$user","$aut");		
	
	if($arr === $pair){
	    
	    // check if the user have balance
	
		$gb = mysqli_query($conn,"SElECT * FROM users WHERE apikey = '$user' ") or die(mysqli_error());	
	$reco = mysqli_fetch_array($gb);
	
	$blc = $reco['bal'];
	$level = $reco['level'];
	$email = $reco['email'];
	$fname = $reco['firstname'];
	$lname = $reco['lastname'];
	
	$query_com = mysqli_query($conn,"SELECT * FROM billing");
	$rate = mysqli_fetch_array($query_com);



	
	$access = 'free';

	    $ikeja = $rate['IkejaElectric'];
		$eko = $rate['EkoElectric'];
		$kano = $rate['Kedc'];
		$kaduna = $rate['kaduna-electric'];
		$jos = $rate['JosElectric'];
		$phed = $rate['Phed'];
		$ibedc = $rate['Ibedc'];
        $aedc = $rate['AbujaElectric'];
		$eedc = $rate['EnuguElectric'];
		$smile = $rate['smile'];

		
		
	if($network === 'ikeja-electric' && $level !== $access){
						
						$per = $ikeja;
						
						$charge = 0;
						
			}elseif($network === 'portharcourt-electric' && $level !== $access){	
										
				$per = $phed;
				
				$charge = 0;	
					}
				elseif($network === 'ibadan-electric' && $level !== $access){
						
					$per = $ibedc;	
					
					$charge = 0;
						}
						elseif($network === 'kano-electric' && $level !== $access){
							
						$per = $kano;
						$charge = 0;	

                        }
						elseif($network === 'kaduna-electric' && $level !== $access){
							
						$per = $kaduna;
						$charge = 0;						
							
							}
						elseif($network === 'jos-electric' && $level !== $access){
								
							$per = $jos;
							$charge = 0;	
								}
						elseif($network === 'eko-electric' && $level !== $access){
								
							$per = $eko;
							$charge = 0;	
								
							}elseif($network === 'smile-direct' && $level !== $access){
							    
							 $per = $smile;
							$charge = 0;

            }elseif($network === 'abuja-electric' && $level !== $access){	
										
				$per = $aedc;
				
				$charge = 0;	
					}
				elseif($network === 'enugu-electric' && $level !== $access){
						
					$per = $eedc;	
					
					$charge = 0;
				}else{
				$per = 10;	
				$charge = 100; }
				
				
		                  if($serviceID === 'ikeja-electric'){
							$disco = "1";
							$pnt = "Ikeja Electricity Payment - IKEDC";
							
							}elseif($serviceID === 'portharcourt-electric'){
                               
								$disco = "4";
								$pnt = "Port Harcourt Electricity Payment - PHED";
								
								}elseif($serviceID === 'ibadan-electric'){
									
									$disco = "6";
									
									$pnt = "Ibadan Electricity Payment - IBEDC";
									
									}elseif($serviceID === 'kano-electric'){
										$disco = "3";
										
										$pnt = "Kano Electricity Payment - KEDCO";
										
										}elseif($serviceID === 'jos-electric'){
											
											$disco = "5";
											
										$pnt = "Jos Electricity Payment - JED";	
										
									}elseif($serviceID === 'eko-electric'){
										$disco = "2";
											
										$pnt = "Eko Electricity Payment - EKEDC";	
											}
											
										elseif($serviceID === 'abuja-electric'){
											$disco = "8";
											
										$pnt = "Abuja Electricity Payment - AEDC";	
											}
											
									elseif($serviceID === 'enugu-electric'){
										$disco = "9";
											
										$pnt = "Enugu Electricity Payment - EEDC";	
											}
											
											
									elseif($serviceID === 'kaduna-electric'){
										$disco = "7";
											
										$pnt = "Kaduna Electricity Payment - KAEDCO";	
											}
											
 $product = $pnt;											
											
		$comi = ($per/100)*$amount;
	$debit1 = $amount - $comi;
	$debit = $debit1 + $charge;
        $chargeAmt = $debit;					
						
						
						
	$debit = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $debit);	
	
	
	if($debit < $blc ){ 
	    
	    // check if ref number exist
	    
	  $req = mysqli_query($conn,"SElECT * FROM transactions WHERE ref = '$ref' ") or die(mysqli_error());	
	$nu = mysqli_num_rows($req);

	if($nu == 0){
	    
       // debit account
	 // $doupt = mysqli_query($conn,"UPDATE users set bal=$blc-$debit WHERE email='$email' ") or die(mysqli_error());

		
$qryApi = mysqli_query($conn,"SELECT * FROM api_setting");
$apidata = mysqli_fetch_array($qryApi);

$key = $apidata['APIkey'];		    


$host = "https://vtuafrica.com.ng/portal/api/electric?apikey=$key&service=$network&meterNo=$meterNo&metertype=$metertype&amount=$amount&ref=$ref";


//Initialize cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$dataR = curl_exec($ch);
$result = json_decode($dataR);
$resp = json_decode($dataR, true);

//Close the cURL handle.
curl_close($ch);

  $message = $result->description->message;
  $token = $result->description->Token;
  $units = $result->description->Units;
  $meter = $result->description->meterNumber;
  $productName = $result->description->product_name;
  $numToken = $token;
  


  if($result->code == '101'){
 


  $message = "TRANSACTION SUCCESSFUL";
    
    $stat = "Completed";

$balA = $blc - $debit;

$doupt = mysqli_query($conn,"UPDATE users SET bal=$blc-$debit WHERE email='$email' ") or die(mysqli_error());


$add = mysqli_query($conn,"INSERT INTO transactions (network,serviceid,channel,meterno,amount,debit,charge,comi,ref,status,email,customer,balanceB,balanceA,del,date) VALUES('$metertype','$product','$channel','$smartNo','$amount','$debit','$charge','$comi','$ref','$stat','$email','$fname $lname','$blc','$balA','$del','$dateTime')") or die(mysqli_error());

 $sto = "INSERT INTO mypin (net,cat,pins,email,ref,amount)VALUES('$pnt','$amount','$token','$email','$ref','$debit')";
	    $prox = mysqli_query($conn,$sto);

response(100,array("status"=>$stat,"Service"=>$pnt,"token"=>$token,"meterNo"=>$meterNo,"metertype"=>$metertype,"Amount_Charged"=>$debit,"Available_Balance"=>$balA,"Transaction_Ref"=>$ref,"transaction_date"=>$dateTime,"message"=>$message));



}else{
	$stat = "Failed";
response(204,array("status"=>$stat,"message"=>$mgs,"ref"=>$ref,"amount"=>$amount,"Amount_Charged"=>'0',"Available_Balance"=>$blc));

}

}else{ response(104,"TRANSACTION ID ALREADY EXIST");
    
    
}
}
// echo low balance
else{ 


    response(102,"LOW BALANCE"); 


    
} 

// close account not found
} else{  
    
    response(103,"INVALID ACCOUNT"); 


    }


} // close wrong parameter



	}   else{ 
	   
	   response(400,"INVALID PARAMETER"); 
	       
	       
	   }
	    

function response($status,$status_message)
{
	
	
	$response['code']=$status;
	$response['description']=$status_message;
	
	
	$json_response = json_encode($response);
	echo $json_response;
}
    
    ?>
    
  
   	

