<?php
// Errors dikhao taaki crash na ho silently
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Log File ka path
$logFile = 'callback_logs.txt';

// 1. Raw Data Capture karo
$rawData = file_get_contents('php://input');
$postData = json_encode($_POST);

// 2. File mein likho (Timestamp ke sath)
$logEntry = "Time: " . date("Y-m-d H:i:s") . "\n";
$logEntry .= "Raw Body: " . $rawData . "\n";
$logEntry .= "POST Data: " . $postData . "\n";
$logEntry .= "-----------------------------------\n";

file_put_contents($logFile, $logEntry, FILE_APPEND);

// 3. Database Connection (Yahan apni config file include karo)
include __DIR__ . "/includes/config.php"; 

// 4. Data Extract karo
$mch_transferId = $_POST['mch_transferId'] ?? null;
$status = $_POST['tradeResult'] ?? null; // 1 = Success

if ($mch_transferId && $status == '1') {
    // Database Update
    $stmt = $conn->prepare("UPDATE withdrawals SET status='completed', updated_at=NOW() WHERE mch_transfer_id=? AND status='processing'");
    $stmt->bind_param("s", $mch_transferId);
    $stmt->execute();
} elseif ($mch_transferId && $status == '2') {
     // Failed logic here
    $stmt = $conn->prepare("UPDATE withdrawals SET status='failed', updated_at=NOW() WHERE mch_transfer_id=?");
    $stmt->bind_param("s", $mch_transferId);
    $stmt->execute();
}

// 5. Gateway ko "success" return karo (Bohot Zaroori)
echo "success";
?>