<?php
include('../includes/session.php');
include('../includes/config.php');

if(!isset($_GET['txn_id'])){die("Invalid Request!");}
$txn_id=mysqli_real_escape_string($ahk_conn,$_GET['txn_id']);
$q=mysqli_query($ahk_conn,"SELECT * FROM recharge_history WHERE agentid='$txn_id' LIMIT 1");
if(mysqli_num_rows($q)==0){die("Transaction not found!");}
$d=mysqli_fetch_assoc($q);

$u="$tng_apiurl/api/RechargeWebService/v1/reacharge-api-status-check?agentid={$txn_id}&apikey={$tng_apikey}";
$c=curl_init();
curl_setopt_array($c,[CURLOPT_URL=>$u,CURLOPT_RETURNTRANSFER=>true]);
$r=curl_exec($c);curl_close($c);
if(!$r){die("API Connection Failed!");}
$j=json_decode($r,true);
if(!$j||!isset($j['Message'])){die("Invalid API Response!");}
$m=$j['Message'];

if(stripos($m,"Success")!==false){
    mysqli_query($ahk_conn,"UPDATE recharge_history SET status='Success',msg='Recharge Success' WHERE agentid='$txn_id'");
    header("Location: reacharge_history.php?msg=success");exit;
}elseif(stripos($m,"Failed")!==false){
    mysqli_query($ahk_conn,"UPDATE recharge_history SET status='Failed',msg='Recharge Failed' WHERE agentid='$txn_id'");
    header("Location: reacharge_history.php?msg=failed");exit;
}elseif(stripos($m,"Refunded")!==false){
    mysqli_query($ahk_conn,"UPDATE recharge_history SET status='Refunded',msg='Recharge Refunded' WHERE agentid='$txn_id'");
    $u=$d['userid'];$a=$d['amount'];
    //mysqli_query($ahk_conn,"UPDATE users SET balance=balance+$a WHERE phone='$u'");
    header("Location: reacharge_history.php?msg=refunded");exit;
}else{
    mysqli_query($ahk_conn,"UPDATE recharge_history SET status='Pending',msg='Recharge Pending' WHERE agentid='$txn_id'");
    header("Location: reacharge_history.php?msg=pending");exit;
}
