<?php
  

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


	// API parameter
    
	if(isset($_REQUEST['apikey']) && isset($_REQUEST['network']) && isset($_REQUEST['DataPlan']) && isset($_REQUEST['quantity']) && isset($_REQUEST['ref']) ){
	
	$apikey = $_REQUEST['apikey'];
	$serviceID = $_REQUEST['network'];
	$quantity = $_REQUEST['quantity'];
	$Dataplan = $_REQUEST['DataPlan'];
	$ref = $_REQUEST['ref'];
	$network = $_REQUEST['network'];
	$name = $_REQUEST['name'];
	$auth = "paid";
	
	$apikey = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $apikey);
	$serviceID = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $serviceID);
	$quantity  = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $quantity);
	$Dataplan = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $Dataplan);
	$ref = str_replace( array( '/', '(', ')',   'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $ref);
	$network = str_replace( array( '+', '-', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $network);
	$name = str_replace( array( '+', '-', '--', '/', '(', ')',   '_',  'drop',  '//', 'delete', 'update', 'insert', '$', '{',   '}',   '<',  '>',  '=', ' ', '  ', '   '), '', $name);
	  
	  if($name == "") {
	  $serName = $_SERVER['SERVER_NAME'];
	  }else{
	  $serName = $name; }	  
	
     $servName = $_SERVER['HTTP_HOST'];
	 $serName;
	
	$convee = '';
	
	$customer = '';
	
	$xname = '';
	
	$action = "Pay";
	
	$dateTime = date('Y-m-d H:m:s');
	$email = $user;
	$proc = '_pay-tv';
	$charge = '';
	$del = "Delete";
	$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'];
	
	$query_com = mysqli_query($conn,"SELECT * FROM sme_data");
	$rate = mysqli_fetch_array($query_com);

	$mtnA = $rate['mtndA'];
	$mtnB = $rate['mtndB'];
	$mtnC = $rate['mtndC'];
	
	
	$airtelA = $rate['airteldA'];
	$airtelB = $rate['airteldB'];
	$airtelC = $rate['airteldC'];

	
	$gloA = $rate['glodA'];
	$gloB = $rate['glodB'];
	$gloC = $rate['glodC'];

	
	
	$etisalatA = $rate['etisalatdA'];
	$etisalatB = $rate['etisalatdB'];
	$etisalatC = $rate['etisalatdC'];

		
		//mtn Data
		if($serviceID == 'mtn' && $Dataplan == '500'  ){
		
		$amount = $mtnA;
		
		$valu = "MTN 500MB";
		$mobplan = "3";
		
		
			
			}elseif($serviceID == 'mtn' && $Dataplan == '1000' ){
				
    		$amount = $mtnB;
    		
    		$valu = "MTN 1GB";
			$mobplan = "5";
			
			
			}elseif($serviceID == 'mtn' && $Dataplan == '1500' ){
				
    		$amount = $mtnC;
    		
    		$valu = "MTN 1.5GB";
			$mobplan = "3";
			
						
						
						
					// airtel Data	
						
	 }elseif($serviceID == 'airtel' && $Dataplan == '500'  ){
		
		$amount = $airtelA;
		
		$valu = "Airtel 500MB";
		$mobplan = "7";
		
		
			
			}elseif($serviceID == 'airtel' && $Dataplan == '1000' ){
				
    		$amount = $airtelB;
    		
    		$valu = "Airtel 1GB";
			$mobplan = "8";
			
			
			}elseif($serviceID == 'airtel' && $Dataplan == '2000' ){
				
    		$amount = $airtelC;
    		
    		$valu = "Airtel 2GB";
			$mobplan = "42";
			
			
							
						//glo data	
							
			}elseif($serviceID == 'glo' && $Dataplan == '500'  ){
		
		$amount = $gloA;
		
		$valu = "Glo 500MB";
		$mobplan = "4";
		
		
			
			}elseif($serviceID == 'glo' && $Dataplan == '1000' ){
				
    		$amount = $gloB;
    		
    		$valu = "Glo 1GB";
			$mobplan = "2";
			
			
			}elseif($serviceID == 'glo' && $Dataplan == '2000' ){
				
    		$amount = $gloC;
    		
    		$valu = "Glo 2GB";
			$mobplan = "82";
			
			
							
							
							//etisalat data
							
							}elseif($serviceID == 'etisalat' && $Dataplan == '500'  ){
		
		$amount = $etisalatA;
		
		$valu = "9Mobile 500MB";
		$mobplan = "9";
		
		
			
			}elseif($serviceID == 'etisalat' && $Dataplan == '1000' ){
				
    		$amount = $etisalatB;
    		
    		$valu = "9Mobile 1GB";
			$mobplan = "10";
			
			
			}elseif($serviceID == 'etisalat' && $Dataplan == '2000' ){
				
    		$amount = $etisalatC;
    		
    		$valu = "9Mobile 2GB";
			$mobplan = "90";
			
			
								
							}else{
							
							$mobplan = "Nil";
							$amount = $Dataplan;	
								
							
								}	
								
								
		  if($network === 'mtn'){
	     $gladNet = "1";
		$service = "MTN DATA CARD";
	
	}elseif($network === 'glo'){
		
		$gladNet = "3";
		$service = "GLO DATA CARD";
		
		}elseif($network === 'etisalat'){
		
		$gladNet = "4";
		$service = "9MOBILE DATA CARD";
			
			}elseif($network === 'airtel'){
				
				$gladNet = "2";
				$service = "AIRTEL DATA CARD";
				
				}else{
				$gladNet = "Nil";
				$service = "Unknown"; }	
				
				
				
		
				
				
		
	     
	
		$comi = ($per/100)*$amount;
		
	$debit = $amount*$quantity;
	
	$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);

$mubkey = $apidata['APIkey'];		    

    $paypload = array(
                    'network' => $gladNet,
                     'plan_type' => $mobplan,
                     'quantity' => $quantity,
                     'card_name' => $serName,
                       );
                       
                     $ch = curl_init();
                     curl_setopt($ch, CURLOPT_URL, 'https://app.mobilesub.com.ng/api/data_card');
                     curl_setopt($ch, CURLOPT_POST, 1);
                     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paypload));
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                     $headers = [
                          "Authorization: Token $mubkey",
                         'Content-Type: application/json'
                     ];
                     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    $response = curl_exec($ch);
                     curl_close($ch);




$json_output = json_decode($response,true);
$result = json_decode($response, true);
 $result1 = json_decode($response);
 
$pin =  $json_output['pin'];
$sn =  $json_output['serial'];
$mgs = $json_output['message'];



if($json_output['status']=="success") {

  $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,phone,amount,charge,ref,status,email,balanceB,balanceA,del,date) VALUES('$service','$valu','$channel','$MobileNumber','$amount','$debit','$ref','$stat','$email','$blc','$balA','$del','$dateTime')") or die(mysqli_error());


  $spac = explode(",", $pin);
$no = count($spac);

foreach($spac as $keys => $show){

//echo $show;
//echo $keys;
//echo '<br>';

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

}


//response(101,array("Status"=>'TRANSACTION SUCCESSFUL')); 

response(101,array("status"=>$stat,"Product"=>$service,"pin"=>$pin,"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;
}
    
    ?>
    
  
   	

