<?php  
session_start();  
error_reporting(E_ALL);  
ini_set('display_errors',1);  
  
require "db.php";  
  
/* ===== ADMIN CHECK ===== */  
if(!isset($_SESSION['admin'])){  
    die("Access Denied");  
}  
  
$apiKey = "sk_live_uqSkHKwJDJjKgrQZR8knNJHHtsSOFK3dybnD";  
  
/* ================= STATS ================= */  
$total = $conn->query("SELECT COUNT(*) as t FROM ipe_requests")->fetch_assoc()['t'];  
$success = $conn->query("SELECT COUNT(*) as t FROM ipe_requests WHERE status='SUCCESSFUL'")->fetch_assoc()['t'];  
$failed = $conn->query("SELECT COUNT(*) as t FROM ipe_requests WHERE status='FAILED'")->fetch_assoc()['t'];  
  
/* ================= CHECK STATUS ================= */  
if(isset($_POST['check_id'])){  
  
    $id = (int)$_POST['check_id'];  
  
    $get = $conn->prepare("SELECT transaction_id FROM ipe_requests WHERE id=?");  
    $get->bind_param("i",$id);  
    $get->execute();  
    $get->bind_result($transaction_id); 
    $get->fetch(); 
    $get->close();  
  
    if($transaction_id){  
  
        $ch = curl_init("https://new.unifyxpress.com/api/v4/transaction/".$transaction_id);  
        curl_setopt_array($ch,[  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_HTTPHEADER=>["X-API-Key: $apiKey"]  
        ]);  
  
        $res = curl_exec($ch);  
        curl_close($ch);  
  
        $response = json_decode($res,true);  
  
        $status = strtoupper($response['status'] ?? 'FAILED');  
        $raw = json_encode($response);  
  
        $stmt = $conn->prepare("UPDATE ipe_requests SET status=?, raw_response=? WHERE id=?");  
        $stmt->bind_param("ssi",$status,$raw,$id);  
        $stmt->execute();  
    }  
  
    header("Location: ipe2_admin.php");  
    exit;  
}  
  
/* ================= RETRY ================= */  
if(isset($_POST['retry_id'])){  
  
    $id = (int)$_POST['retry_id'];  
  
    $get = $conn->prepare("SELECT tracking_id FROM ipe_requests WHERE id=?");  
    $get->bind_param("i",$id);  
    $get->execute();  
    $get->bind_result($tracking_id);  
    $get->fetch();  
    $get->close();  
  
    if($tracking_id){  
  
        $payload = json_encode(["tracking_ids"=>[$tracking_id]]);  
  
        $ch = curl_init("https://new.unifyxpress.com/api/v4/nin/ipe");  
        curl_setopt_array($ch,[  
            CURLOPT_RETURNTRANSFER=>true,  
            CURLOPT_POST=>true,  
            CURLOPT_POSTFIELDS=>$payload,  
            CURLOPT_HTTPHEADER=>[  
                "Content-Type: application/json",  
                "X-API-Key: $apiKey"  
            ]  
        ]);  
  
        $res = curl_exec($ch);  
        curl_close($ch);  
  
        $data = json_decode($res,true);  
  
        if(isset($data['transactions'][0])){  
            $t = $data['transactions'][0];  
  
            $raw = json_encode($t);  
  
            $stmt = $conn->prepare("UPDATE ipe_requests SET transaction_id=?, status=?, raw_response=? WHERE id=?");  
            $stmt->bind_param("sssi",$t['id'],$t['status'],$raw,$id);  
            $stmt->execute();  
        }  
    }  
  
    header("Location: ipe2_admin.php");  
    exit;  
}  
  
/* ================= UPDATE STATUS / REPLY ================= */  
if(isset($_POST['update_id'])){  
  
    $id = (int)$_POST['update_id'];  
    $status = $_POST['status'];  
    $reply = $_POST['reply'];  
  
    $stmt = $conn->prepare("UPDATE ipe_requests SET status=?, reply=? WHERE id=?");  
    $stmt->bind_param("ssi",$status,$reply,$id);  
    $stmt->execute();  
  
    header("Location: ipe2_admin.php");  
    exit;  
}  
  
/* ================= FETCH ================= */  
$data = $conn->query("SELECT * FROM ipe_requests ORDER BY id DESC");  
?>  <!DOCTYPE html>  <html>  
<head>  
<title>Admin IPE</title>  <style>  
body{background:#071a2f;color:#fff;font-family:Arial;padding:20px}  
  
/* TOP BOXES */  
.top-box{display:flex;gap:15px;margin-bottom:20px;flex-wrap:wrap}  
.card{flex:1;background:#0b2545;padding:20px;border-radius:10px;text-align:center}  
.card h2{margin:0}  
  
/* TABLE */  
table{width:100%;border-collapse:collapse;background:#0b2545}  
th,td{padding:10px;border-bottom:1px solid #333;text-align:center}  
  
/* BUTTONS */  
.btn{padding:6px 10px;border:none;cursor:pointer}  
.check{background:#ffaa00}  
.retry{background:#00c896}  
.update{background:#007bff;color:#fff}  
  
/* FORM */  
input,select{padding:5px;width:90%}  
  
/* POPUP */  
.popup{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);align-items:center;justify-content:center;}  
.popup-box{background:#fff;width:90%;max-width:400px;border-radius:10px;}  
.popup-header{background:#0b2545;color:#fff;padding:10px;display:flex;justify-content:space-between;}  
.popup-body{padding:15px;color:#000;}  
</style>  </head>  <body>  <h2>Admin IPE Dashboard</h2>  <!-- TOP STATS -->  <div class="top-box">  
<div class="card">  
<h2><?=$total?></h2>  
<p>Total Requests</p>  
</div>  <div class="card">  
<h2><?=$success?></h2>  
<p>Successful</p>  
</div>  <div class="card">  
<h2><?=$failed?></h2>  
<p>Failed</p>  
</div>  
</div>  <table>  
<tr>  
<th>ID</th>  
<th>User</th>  
<th>Tracking</th>  
<th>Status</th>  
<th>Report</th>  
<th>Actions</th>  
<th>Update</th>  
</tr>  <?php while($row=$data->fetch_assoc()): ?>  <tr>  <td><?=$row['id']?></td>  
<td><?=$row['user']?></td>  
<td><?=$row['tracking_id']?></td>  
<td><?=$row['status']?></td>  <td>  
<?php if($row['raw_response'] || $row['reply']): ?>  
<button onclick="viewReport(`<?=htmlspecialchars($row['raw_response'] ?: $row['reply'],ENT_QUOTES)?>`)">  
View  
</button>  
<?php else: ?>--<?php endif; ?>  
</td>  <td>  <form method="post" style="display:inline;">  
<input type="hidden" name="check_id" value="<?=$row['id']?>">  
<button class="btn check">Check</button>  
</form>  <form method="post" style="display:inline;">  
<input type="hidden" name="retry_id" value="<?=$row['id']?>">  
<button class="btn retry" onclick="return confirm('Retry this request?')">Retry</button>  
</form>  </td>  <td>  
<form method="post">  
<input type="hidden" name="update_id" value="<?=$row['id']?>">  <select name="status">  
<option value="PENDING">PENDING</option>  
<option value="SUCCESSFUL">SUCCESSFUL</option>  
<option value="FAILED">FAILED</option>  
</select>  <input type="text" name="reply" placeholder="Reply">  <button class="btn update">Save</button>

</form>  
</td>  </tr>  
<?php endwhile; ?>  
</table>  <!-- POPUP -->  <div id="popup" class="popup">  
<div class="popup-box">  
<div class="popup-header">  
<span>Report</span>  
<span onclick="closePop()">✖</span>  
</div>  
<div class="popup-body" id="content"></div>  
</div>  
</div>  <script>  
function viewReport(data){  
let html="";  
try{  
let d=JSON.parse(data);  
html+="<b>Status:</b> "+(d.status||'N/A')+"<br><br>";  
html+="<b>Tracking:</b> "+(d.data?.tracking_id||'N/A')+"<br><br>";  
html+="<b>NIN:</b> "+(d.data?.nin||'N/A');  
}catch{  
html=data;  
}  
document.getElementById("content").innerHTML=html;  
document.getElementById("popup").style.display="flex";  
}  
  
function closePop(){  
document.getElementById("popup").style.display="none";  
}  
</script>  </body>  
</html>