<?php
// check_status.php — Manually check status when callback fails
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

// Kis ID ko check karna hai? (URL se lo, e.g., check_status.php?id=15)
if (!isset($_GET['id'])) { die("Please provide withdrawal ID (e.g., check_status.php?id=123)"); }
$id = (int)$_GET['id'];

// 1. Database se Order Details nikalo
$stmt = $conn->prepare("SELECT * FROM withdrawals WHERE id=? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if (!$row) { die("Transaction not found in Database."); }

// Agar pehle se success hai to check mat karo
if ($row['status'] == 'completed') { die("✅ Already Completed."); }

echo "<h3>Checking Status for Request ID: $id</h3>";
echo "Merchant Transfer ID: " . $row['mch_transfer_id'] . "<br>";

// ==========================================
// CONFIGURATION (Same as Payout File)
// ==========================================
$merchant_id   = "100888128"; 
$merchant_key  = "KOROZSWLYD8TI4JYGUNI72RWFJPZHQ1V"; 
$query_url     = "https://api.watchglb.com/query/transfer"; // Doc wala URL

// ==========================================
// PREPARE REQUEST
// ==========================================
$mch_transferId = $row['mch_transfer_id'];

// Signature Logic for Query (Doc: mch_id + mch_transferId + key)
$signStr = "mch_id=" . $merchant_id . "&mch_transferId=" . $mch_transferId . "&key=" . $merchant_key;
$sign = md5($signStr);

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

// ==========================================
// CALL API
// ==========================================
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $query_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Query API often requires this header
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

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

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

echo "<hr><strong>Gateway Response:</strong><br>";
echo "<pre>" . print_r($json, true) . "</pre><hr>";

if (isset($json['respCode']) && $json['respCode'] == 'SUCCESS') {
    
    // Trade Result: 1 = Success, 2 = Fail, 4 = Processing
    $tradeResult = $json['tradeResult'];

    if ($tradeResult == '1') {
        // SUCCESS
        $update = $conn->prepare("UPDATE withdrawals SET status='completed', updated_at=NOW() WHERE id=?");
        $update->bind_param("i", $id);
        $update->execute();
        echo "<h2 style='color:green'>✅ Status Updated to SUCCESS!</h2>";
        
    } elseif ($tradeResult == '2') {
        // FAILED - Refund Logic
        echo "<h2 style='color:red'>❌ Transfer Failed. Refunding...</h2>";
        
        $conn->begin_transaction();
        try {
            // Update withdrawal status
            $stmt = $conn->prepare("UPDATE withdrawals SET status='failed', remark=? WHERE id=?");
            $failMsg = "Gateway Check: Failed";
            $stmt->bind_param("si", $failMsg, $id);
            $stmt->execute();

            // Refund Money
            $stmt = $conn->prepare("UPDATE users SET income_balance = income_balance + ? WHERE id=?");
            $stmt->bind_param("di", $row['amount'], $row['user_id']);
            $stmt->execute();

            $conn->commit();
            echo "Refund Complete.";
            
        } catch (Exception $e) {
            $conn->rollback();
            echo "Error during refund: " . $e->getMessage();
        }

    } elseif ($tradeResult == '4') {
        echo "<h2 style='color:orange'>⏳ Still Processing... Check again later.</h2>";
    } else {
        echo "<h2>Unknown Status Code: $tradeResult</h2>";
    }

} else {
    echo "<h3 style='color:red'>API Error or Invalid Signature</h3>";
}
?>