<?php
    session_start();
	if($_SESSION['adm'])
	{
		$userid= $_SESSION['adm'];
	}
	else
	{
		header('location:../login.php');
	}
?>
<?php
    include'connection.php';
	
	date_default_timezone_set("asia/Kolkata");
	$date= Date("Y-m-d");
    $time= Date("h:i:s A");
    
    if(isset($_POST['submit']))
    {
        $SelectApi=$_POST['api'];
	    $rehit=$_POST['rehit'];
	    
		$queryPR="select * from recharge where Status='PENDING' and ReHit='$rehit' and Rechargedate='$date'";
		$resultPR=mysqli_query($con,$queryPR);
		
		while($dataGetRech=mysqli_fetch_array($resultPR))
		{
			$rechId=$dataGetRech['Id'];
			$mnum=$dataGetRech['Mobile'];
			$amount=$dataGetRech['Amount'];
			$operator=$dataGetRech['Companyname'];
			$userid=$dataGetRech['Userid'];
			$postpaidOperator=substr($operator, -8);
		    
			$newrechid=$rechId;
		    
			$opcodequery="select * from operator where Operator='$operator'";
			$opcoderesult=mysqli_query($con,$opcodequery);
			$opcodedata=mysqli_fetch_array($opcoderesult);
			$opcode=$opcodedata['Value'];
			$myApiOpCode=$opcodedata['MyApiValue'];
			$MyApi2OpCode=$opcodedata['My_API2'];
			$KwikApiOpCode=$opcodedata['KwikAPI'];
			$UniqueApiOpCode=$opcodedata['UniqueAPI'];
			$DiziPayOpCode=$opcodedata['DiziPayApi'];
			
			$UseApiByDefault=$opcodedata['UseAPI'];
			
			if($SelectApi=="BD")
			{
			    $UseApi=$UseApiByDefault;
			}
			else
			{
			    $UseApi=$SelectApi;
			}
         
            if($UseApi=="My_API")
			{
			    $queryUpadateOrderId="update recharge set ReHit='0', API='My_API' where Id='$newrechid'";
				mysqli_query($con,$queryUpadateOrderId);
				
				$token="01dc7e7d-ec4d-42db-99b4-cdf62a80a72a";
				$url="https://www.vastwebindia.com/API/API/Recharge?Mobile=$mnum&OptCode=$myApiOpCode&Amount=$amount&Token=$token&Userid=sameermansuri111@gmail.com&rch_id=$newrechid";
				
				$curl = curl_init();

                curl_setopt_array($curl, array(
                CURLOPT_URL => "https://www.vastwebindia.com/API/API/Recharge?Mobile=$mnum&OptCode=$myApiOpCode&Amount=$amount&Token=$token&Userid=sameermansuri111@gmail.com&rch_id=$newrechid",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "GET",
                CURLOPT_POSTFIELDS => "",
                CURLOPT_HTTPHEADER => array(
                "Postman-Token: 7d11312d-5948-4352-be19-b636152e59fd",
                "cache-control: no-cache"),));

                $response = curl_exec($curl);
                $err = curl_error($curl);

                curl_close($curl);

                if ($err) {
                  echo "cURL Error #:" . $err;
                } else
                {
                    echo   $response;
                }
			}                               
			elseif($UseApi=="My_API2")
			{   
			    $UpdateRechApibal="update recharge set API='My_API2' where Id='$newrechid'";
			    mysqli_query($con,$UpdateRechApibal);
											    		
				$ch = curl_init();

                if (!$ch)
				{
                    die("Couldn't initialize a cURL handle");
                }
                curl_setopt($ch, CURLOPT_URL,'https://mrobotics.in/api/recharge?'); // Target URL
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS,"api_token=37a1e7bd-3d24-4d73-8c17-ecd76d5a847e&mobile_no=$mnum&amount=$amount&company_id=$MyApi2OpCode&order_id=$newrechid&is_stv=false");

                $result = curl_exec ($ch); 

                $result = (array)json_decode($result);
                                                            
                $status1 = $result['status'];
                $errorMsg = $result['errorMessage'];   
                $msg = $result['response'];   
                $txnId = $result['tnx_id'];   
                $LapuNo = $result['lapu_no'];   
                $LapuBal = $result['balance'];   
                                                                
				if($status1=="SUCCESS" || $status1=="success")
				{
					$GetLapuOldBal="select * from recharge where LapuNo='$LapuNo' and status='SUCCESS' order by Id desc";
					$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
					$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
					$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
					$remaiBal=$LapuOldBal-$amount;
					$LapuDiff = $LapuBal-$remaiBal;
					$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='SUCCESS', Operatorid='$txnId', LapuOldBal='$LapuOldBal', Diff='$LapuDiff', API='My_API2', LapuNo='$LapuNo', ApiBal='$LapuBal' where Id='$newrechid'";
					mysqli_query($con,$queryUpadateOrderId);
					
					$quUpdatebal="update myapi set LapuBal='$LapuBal' where LapuNumber='$LapuNo'";
					mysqli_query($con,$quUpdatebal);
					echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfully !</font></h1><br>";
								
				}
				else
				{
					echo $result;
				}
			}
			elseif($UseApi=="Kwik_API")
			{
				$queryUpadateOrderId="update recharge set ReHit='0', API='Kwik_API' where Id='$newrechid'";
				mysqli_query($con,$queryUpadateOrderId);
												
												
				$apikey="8tyeubd-prieyeiw-854125-75yhr-8454adz";
				if($postpaidOperator=="Postpaid")
				{
					$url="https://www.kwikapi.com/api/v2/bills/recharge.php?api_key=$apikey&number=$mnum&amount=$amount&opid=$KwikApiOpCode&state_code=0&order_id=$newrechid";
											        
					$curl = curl_init();
					curl_setopt_array($curl, array(
					CURLOPT_URL => $url,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",));
	
					$response = curl_exec($curl);
					$err = curl_error($curl);
	
					curl_close($curl);
	
					if ($err)
					{
						echo "cURL Error #:" . $err;
					}
					else
					{
						echo $response;
					}
												
			    }
			    else
			    {
			        echo $url="https://www.kwikapi.com/api/v2/recharge.php?api_key=$apikey&number=$mnum&amount=$amount&opid=$KwikApiOpCode&state_code=0&order_id=$newrechid";
											        
					$curl = curl_init();
					curl_setopt_array($curl, array(
					CURLOPT_URL => $url,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",));
	
					$response = curl_exec($curl);
					$err = curl_error($curl);
	
					curl_close($curl);
	
					if ($err)
					{
						echo "cURL Error #:" . $err;
					}
					else
					{
						echo $response;
						$data2=json_decode($response);
													
						$status1 = $data2->status;
						$resText = $data2->message;
						$txnId = $data2->opr_id;
						$kwikApiBal = $data2->balance;
													
						if($status1=="SUCCESS")
						{
							$queryUpadateOrderId="update recharge set Transactionid='$orderId', AdminOpId='S', Status='$status1', Operatorid='$txnId', API='Kwik_API', ApiBal='$kwikApiBal' where Id='$newrechid'";
							mysqli_query($con,$queryUpadateOrderId);
							echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfull !</font></h1><br>";
						}
						elseif($status1=="FAILED")
						{
						    $UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText' where Id='$newrechid'";
	                        mysqli_query($con,$UpdateRechApibal);
						}
					}
				}
			}
			elseif($UseApi=="DiziPay_Api")
			{   
			    $UpdateRechApibal="update recharge set API='DiziPay_Api' where Id='$newrechid'";
				mysqli_query($con,$UpdateRechApibal);
				
                $ApiKey="qYpom1zuu0%2bJMfK1iuYr%2fITnSZFQPeFEAE%2fdl%2fo69mY%3d";
                $ApiPwd="123456";
                $url="http://login.dizi-pay.com/retailer/api/do_recharge_transaction.aspx?key=$ApiKey&password=$ApiPwd&mobile=$mnum&amount=$amount&opcode=JR&requestid=$newrechid";
    
		        $request_timeout = 60;
		        $ch = curl_init();
		        curl_setopt($ch, CURLOPT_URL, $url);
		        curl_setopt($ch, CURLOPT_TIMEOUT, $request_timeout);
		        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_timeout);
		        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	            $output = curl_exec($ch);
		        $curl_error = curl_errno($ch);
		        $getserver= curl_getinfo($ch);
		        curl_close($ch);
		        $xml = simplexml_load_string(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $output));
		
                $status1 = $xml->Status;  
                $msg = $xml->MSG;   
                $txnId = $xml->TransID;   
                $OrderID = $xml->OrderID;    
                                                                
				if($status1=="SUCCESS")
				{
					$GetLapuOldBal="select * from recharge where LapuNo='DiziPay_Api' and status='SUCCESS' order by Id desc";
					$reGetLapuOldBal=mysqli_query($con,$GetLapuOldBal);
					$dataGetLapuOldBal=mysqli_fetch_array($reGetLapuOldBal);
					$LapuOldBal=$dataGetLapuOldBal['ApiBal'];
					$remaiBal=$LapuOldBal-$amount;
					$LapuDiff = $DiziPayApiBal-$remaiBal;
					$queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='SUCCESS', Operatorid='$txnId', LapuOldBal='$LapuOldBal', Diff='$LapuDiff', API='DiziPay_Api', LapuNo='DiziPay_Api', ApiBal='$DiziPayApiBal' where Id='$newrechid'";
					mysqli_query($con,$queryUpadateOrderId);
						
					echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfully !</font></h1><br>";
								
				}
				elseif($status1=="PROCESSED")
				{   
					$queryUpadateOrderId="update recharge set Transactionid='$OrderID', Status='PENDING', Operatorid='$txnId', LapuOldBal='$LapuOldBal', Diff='$LapuDiff', API='My_API2', LapuNo='$LapuNo', ApiBal='$LapuBal' where Id='$newrechid'";
					mysqli_query($con,$queryUpadateOrderId);
						
					echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfully !</font></h1><br>";
				}
				elseif($status1=="FAILED" || $status1=="FAILURE")
				{
					if($AutoFailedStatus=="Deactive")
					{
						$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$msg', API='My_API2' where Id='$newrechid'";
						mysqli_query($con,$UpdateRechApibal);
					}
					else
					{
					    $refundquery="select * from wallet where Userid='$userid' order by Id desc";
						$refundresult=mysqli_query($con,$refundquery);
						$refunddata=mysqli_fetch_array($refundresult);
						$refundoldbal=$refunddata['Balance'];
						$refundnewbal=$refundoldbal+$actual;
						
						$refundaddbalquery="insert into wallet(Userid,Openingbalance,Credit,Remarks,Balance,Date,Time,Transactiontype,Paynrechid,Operator,Mobile,Amount,Status)
						values('$userid','$refundoldbal','$actual','Recharge_Refund','$refundnewbal','$date','$time','Recharge_Refund','$newrechid','$operator','$mnum','$amount','$status')";
						if(mysqli_query($con,$refundaddbalquery))
						{
							$getrefundewalletid="select * from wallet where Userid='$userid' order by Id desc";
							$resultrefundewalletid=mysqli_query($con,$getrefundewalletid);
							$datarefundewalletid=mysqli_fetch_array($resultrefundewalletid);
							$refundewalletid=$datarefundewalletid['Id'];
																	
							$failedquery="update recharge set Creditewalletid='$refundewalletid', Status='FAILED', Transactionid='$orderId', Operatorid='$errorMsg, $msg', Responsetxt='$resText', API='DiziPay_Api' where Id='$newrechid'";
							mysqli_query($con,$failedquery);
							
							$deletecomm="delete from commwallet where Rechargeid='$newrechid'";
							mysqli_query($con,$deletecomm);
						
							$query9="update retailer set Balance='$refundnewbal' where Userid='$userid'";
							mysqli_query($con,$query9);
							
							echo "<h1 align='center'><font color='#ff0000'> &#x2716; Your Recharge Request Has Been Failed Now !</font></h1>";
																
						}
					}
			    }
			}
			elseif($UseApi=="Unique_API")
			{
			    $queryUpadateOrderId="update recharge set ReHit='0', API='Unique_API' where Id='$newrechid'";
				mysqli_query($con,$queryUpadateOrderId);
			    
				$apiUserId="9897095971";
				$apiPwd="123456";
				$curl = curl_init();

				curl_setopt_array($curl, array(
				CURLOPT_URL => "http://uniqueebazaar.store/index.php/RechargeWebService/apitransaction?userid=9897095971&password=123456&mobile=$mnum&opt=$UniqueApiOpCode&amount=$amount&agentid=$newrechid&fmt=json",
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => "",
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 30,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => "POST",
				CURLOPT_POSTFIELDS => "",
				CURLOPT_HTTPHEADER => array(
				"Postman-Token: 12172b3e-8111-46ff-a491-71ca0f581b7e",
				"cache-control: no-cache"),));

                $response = curl_exec($curl);
                $err = curl_error($curl);

                curl_close($curl);
												
				if ($err)
				{
					echo "cURL Error #:" . $err;
				}
				else
				{
					echo $response;
					
				}
			}
			elseif($UseApi=="Rech_API")
			{	
			    $UpdateRechApibal="update recharge set ReHit='0', API='Rech_API' where Id='$newrechid'";
				mysqli_query($con,$UpdateRechApibal);
				
				$token="4x9tiI9Zz7Sxmi3G8qvhpczsijBLBt";
				$url="http://api.rechapi.com/recharge.php?format=xml&token=$token&mobile=$mnum&amount=$amount&opid=$opcode&urid=$newrechid";
				$request_timeout = 60; // 60 seconds timeout
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_TIMEOUT, $request_timeout);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_timeout);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				$output = curl_exec($ch);
				$curl_error = curl_errno($ch);
				$getserver= curl_getinfo($ch);
				curl_close($ch);
				if($getserver["http_code"]==200)
				{
												
					$xml = simplexml_load_string($output);
					$orderId=$xml->orderId;
					$status1=$xml->status;
					$mobile=$xml->mobile;
					$amount=$xml->amount;
					$operatorId=$xml->operatorId;
					$error_code=$xml->error_code;
					$service=$xml->service;
					$resText=$xml->resText;
					if($status1=="PENDING")
					{
						$queryUpadateOrderId="update recharge set Transactionid='$orderId', API='Rech_API' where Id='$newrechid'";
						mysqli_query($con,$queryUpadateOrderId);
						echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfull !</font></h1><br>";
					}
					elseif($status1=="SUCCESS")
					{
					    $queryUpadateOrderId="update recharge set Transactionid='$orderId', Status='SUCCESS', API='Rech_API', AdminOpId='S' where Id='$newrechid'";
						mysqli_query($con,$queryUpadateOrderId);
						echo "<h1 align='center'><font color='#008000'> &#x2714; Your Request Submit Successfull !</font></h1><br>";
					}
					elseif($status1=="FAILED")
					{
					    $UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', Transactionid='$orderId' where Id='$newrechid'";
	                       mysqli_query($con,$UpdateRechApibal);
	                       echo "<h1 align='center'><font color='#ff0000'> &#x2716; Your Recharge Request Has Been Failed Now !</font></h1>";
					}							
				}
				elseif($curl_error=="28")
				{
					$UpdateRechApibal="update recharge set ReHit='1', AdminOpId='$resText', Transactionid='$orderId' where Id='$newrechid'";
	                mysqli_query($con,$UpdateRechApibal);
	                echo "<h1 align='center'><font color='#ff0000'> &#x2716; Your Recharge Request Has Been Failed Now !</font></h1>";
				}
											
			}
		}
    }

?>
<html>
<head>
       <style>
        INPUT{width:200px; height:40px; font-size:22px; margin:10px;}
        SELECT{width:200px; height:40px; font-size:22px; margin:10px; text-align:center;}
        table{border-collapse:collapse;}
        table th{width:200px; height:40px; font-size:22px; margin:10px;}
       </style>
</head>
<body>
<form method="post">
    <table border="1" cellpadding="10">
        <tr>
            <th>Recharge Type</th>
            <th>Use API</th>
            <th>Action</th>
        </tr>
        <tr>
            <td>
                <select name="rehit">
                    <option value="1">FAILDED</option>
                    <option value="0">PENDINGED</option>
                </select>
            </td>
            <td>
                <select name="api">
                    <option value="BD">BY DEFAULT</option>
                    <option value="My_API">MY API</option>
                    <option value="My_API2">My API2</option>
                    <option value="Unique_API">Unique API</option>
                    <option value="Kwik_API">Kwik API</option>
                    <option value="Rech_API">Rech API</option>
                    <option value="DiziPay_Api">DiziPay_Api</option>
                </select>
            </td>
            <td>
                <input type="submit" name="submit" value="ReHit All">
            </td>
    <table>
</form>
</body>
</html>