<?php
session_start();
require "db.php";

if(!isset($_SESSION['admin'])){
    die("Admin only");
}

$API_KEY = "sk_live_uqSkHKwJDJjKgrQZR8knNJHHtsSOFK3dybnD";

/* ================= UPDATE ================= */
if(isset($_POST['update'])){

    $id = (int)$_POST['id'];
    $bvn = trim($_POST['bvn']);
    $status = strtoupper(trim($_POST['status']));
    $reply = trim($_POST['reply']);

    $stmt = $conn->prepare("
        UPDATE bvn_phone_logs 
        SET bvn=?, status=?, reply=? 
        WHERE id=?
    ");
    $stmt->bind_param("sssi",$bvn,$status,$reply,$id);
    $stmt->execute();
    $stmt->close();

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= RETRY ================= */
if(isset($_POST['retry'])){

    $id = (int)$_POST['id'];

    $stmt = $conn->prepare("SELECT phone FROM bvn_phone_logs WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();

    if($row){

        $url = "https://new.unifyxpress.com/api/v4/verify/bvn";

        $data = json_encode(["phone"=>$row['phone']]);

        $ch = curl_init($url);
        curl_setopt_array($ch,[
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_POST=>true,
            CURLOPT_POSTFIELDS=>$data,
            CURLOPT_HTTPHEADER=>[
                "Content-Type: application/json",
                "X-API-Key: $API_KEY"
            ]
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($response,true);

        $status = "PENDING";
        $bvn = "";
        $trx_id = null;
        $reply = "";

        if(!empty($result['status'])){
            $status = strtoupper(trim($result['status']));
        }

        if(!empty($result['id'])){
            $trx_id = $result['id'];
        }

        if(isset($result['data']) && !empty($result['data']['bvn'])){
            $bvn = $result['data']['bvn'];
            $status = "SUCCESS";
        }

        if(!empty($result['remark'])){
            $reply = $result['remark'];
        }

        $stmt = $conn->prepare("
            UPDATE bvn_phone_logs 
            SET bvn=?, status=?, transaction_id=?, reply=? 
            WHERE id=?
        ");
        $stmt->bind_param("ssssi",$bvn,$status,$trx_id,$reply,$id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= CHECK STATUS (FIXED) ================= */
if(isset($_POST['check_status'])){

    $id = (int)$_POST['id'];

    $stmt = $conn->prepare("SELECT transaction_id, status, bvn FROM bvn_phone_logs WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();

    if(!empty($row['transaction_id'])){

        $trx_id = $row['transaction_id'];

        // ✅ FIXED ENDPOINT
        $url = "https://new.unifyxpress.com/api/v4/transaction/".$trx_id;

        $ch = curl_init($url);
        curl_setopt_array($ch,[
            CURLOPT_RETURNTRANSFER=>true,
            CURLOPT_HTTPHEADER=>[
                "X-API-Key: $API_KEY"
            ]
        ]);

        $response = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($response,true);

        $status = $row['status'];
        $bvn = $row['bvn'];
        $reply = "";

        if(!empty($result['status'])){
            $status = strtoupper(trim($result['status']));
        }

        if(isset($result['data']) && !empty($result['data']['bvn'])){
            $bvn = $result['data']['bvn'];
        }

        if(!empty($result['remark'])){
            $reply = $result['remark'];
        }

        $stmt = $conn->prepare("
            UPDATE bvn_phone_logs 
            SET bvn=?, status=?, reply=? 
            WHERE id=?
        ");
        $stmt->bind_param("sssi",$bvn,$status,$reply,$id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= REFUND ================= */
if(isset($_POST['refund'])){

    $id = (int)$_POST['id'];

    $stmt = $conn->prepare("SELECT user_email, status, refunded FROM bvn_phone_logs WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();

    if($row){

        if(in_array($row['status'], ['FAILED','REJECTED']) && $row['refunded']==0){

            $email = $row['user_email'];

            $conn->query("UPDATE balance SET amount = amount + 800 WHERE user='$email'");

            $stmt = $conn->prepare("UPDATE bvn_phone_logs SET refunded=1 WHERE id=?");
            $stmt->bind_param("i",$id);
            $stmt->execute();
            $stmt->close();
        }
    }

    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

/* ================= DATA ================= */
$res=$conn->query("SELECT * FROM bvn_phone_logs ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
<title>BVN Admin</title>

<style>
body{background:#071a2f;color:#fff;font-family:Arial;padding:20px}
.topbar{margin-bottom:15px}
.topbar a{background:#00bfff;color:#fff;padding:8px 12px;text-decoration:none;border-radius:6px}
table{width:100%;border-collapse:collapse;background:#fff;color:#000}
th,td{padding:10px;border-bottom:1px solid #ddd}
th{background:#0b2545;color:#fff}
button{padding:6px 10px;border:none;cursor:pointer}
.update{background:#00bfff;color:#fff}
.retry{background:#ff9800;color:#fff}
.check{background:#4caf50;color:#fff}

.PENDING{color:orange;font-weight:bold}
.SUCCESS{color:green;font-weight:bold}
.FAILED{color:red;font-weight:bold}
.REJECTED{color:red;font-weight:bold}
</style>

<script>
function confirmRetry(){
    return confirm("Are you sure you want to retry this request?");
}
</script>

</head>

<body>

<div class="topbar">
<a href="admin_dashboard.php">⬅ Back to Dashboard</a>
</div>

<h2>BVN Admin Dashboard</h2>

<table>

<tr>
<th>User</th>
<th>Phone</th>
<th>BVN</th>
<th>Status</th>
<th>Reply</th>
<th>Transaction ID</th>
<th>Date</th>
<th>Action</th>
</tr>

<?php while($row=$res->fetch_assoc()): ?>

<tr>
<form method="post">

<td><?=$row['user_email']?></td>
<td><?=$row['phone']?></td>

<td><input type="text" name="bvn" value="<?=htmlspecialchars($row['bvn'])?>"></td>

<td class="<?=strtoupper($row['status'])?>">
<select name="status">
<option value="PENDING" <?=$row['status']=='PENDING'?'selected':''?>>PENDING</option>
<option value="SUCCESS" <?=$row['status']=='SUCCESS'?'selected':''?>>SUCCESS</option>
<option value="FAILED" <?=$row['status']=='FAILED'?'selected':''?>>FAILED</option>
<option value="REJECTED" <?=$row['status']=='REJECTED'?'selected':''?>>REJECTED</option>
</select>
</td>

<td><input type="text" name="reply" value="<?=htmlspecialchars($row['reply'])?>"></td>

<td><?=$row['transaction_id']?></td>
<td><?=$row['created_at']?></td>

<td>
<input type="hidden" name="id" value="<?=$row['id']?>">

<button class="update" name="update">Update</button>
<button class="retry" name="retry" onclick="return confirmRetry()">Retry</button>
<button class="check" name="check_status">Check</button>

<?php if(in_array($row['status'], ['FAILED','REJECTED']) && $row['refunded']==0): ?>
<button name="refund" style="background:red;color:#fff"
onclick="return confirm('Refund ₦800 to user?')">Refund</button>
<?php elseif($row['refunded']==1): ?>
<span style="color:green;font-weight:bold">Refunded</span>
<?php endif; ?>

</td>

</form>
</tr>

<?php endwhile; ?>

</table>

</body>
</html>