<?php
// admin_check_status.php — Check Status of Payout from Gateway
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
include __DIR__ . "/includes/config.php"; 
include __DIR__ . "/signapi.php"; 

if (!isset($_SESSION['admin_id'])) {
    die("Access Denied");
}

if (!isset($_GET['id'])) {
    die("Invalid Request");
}

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

// 1. Withdrawal Details Nikalo
$stmt = $conn->prepare("SELECT mch_transfer_id, user_id, amount FROM withdrawals WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();

if (!$row || empty($row['mch_transfer_id'])) {
    echo "<script>alert('Transaction ID (mch_transfer_id) not found! Cannot check status.'); window.location.href='withdraw_requests.php';</script>";
    exit();
}

$mch_transferId = $row['mch_transfer_id'];

// ---------------------------------------------------
// ⚙️ GATEWAY CONFIG
// ---------------------------------------------------
$merchant_id  = "100888128";
$merchant_key = "ea09080a2b00433b8d8a74e7cb7aac6e"; 
$query_url    = "https://api.watchglb.com/pay/transfer_query"; // Status Check URL

// ---------------------------------------------------
// 🔐 GENERATE SIGNATURE
// ---------------------------------------------------
$signStr = "";
$signStr .= "mch_id=" . $merchant_id . "&";
$signStr .= "mch_transferId=" . $mch_transferId;

$signAPI = new signapi();
$sign = $signAPI->sign($signStr, $merchant_key);

$postdata = array(
    'mch_id'         => $merchant_id,
    'mch_transferId' => $mch_transferId,
    'sign_type'      => 'MD5',
    'sign'           => $sign
);

// ---------------------------------------------------
// 🚀 SEND QUERY
// ---------------------------------------------------
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postdata));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

// ---------------------------------------------------
// 📊 HANDLE RESPONSE
// ---------------------------------------------------
$json = json_decode($response, true);

if (isset($json['tradeResult']) && $json['tradeResult'] == 1) {
    // ✅ SUCCESS: Gateway bol raha hai payment ho gayi
    
    // Update DB to 'successful' (Agar pehle nahi tha)
    $conn->query("UPDATE withdrawals SET status='successful' WHERE id=$id");
    
    echo "<script>alert('✅ Gateway Status: SUCCESS! Database Updated.'); window.location.href='withdraw_requests.php';</script>";

} elseif (isset($json['tradeResult']) && $json['tradeResult'] == 2) {
    // ❌ FAILED: Gateway bol raha hai payment fail ho gayi
    
    // Refund Logic (Agar abhi tak pending/approved hai to reject karke refund karo)
    // Note: Isse automatic refund karna risky ho sakta hai, isliye sirf alert dikhate hain
    echo "<script>alert('❌ Gateway Status: FAILED! Reason: " . ($json['tradeMsg'] ?? 'Unknown') . "'); window.location.href='withdraw_requests.php';</script>";

} else {
    // ⏳ PROCESSING / UNKNOWN
    $msg = $json['tradeMsg'] ?? 'Processing or Not Found';
    echo "<script>alert('⚠️ Status: $msg'); window.location.href='withdraw_requests.php';</script>";
}
?>