<?php
// CONFIGURATION
$secretKey = "ioQxXoydAMbfcyKhDTYr"; // ← apna actual payout key yahaan daalen

// READ raw POST data
$input = json_decode(file_get_contents("php://input"), true);

// LOG REQUEST (optional for debugging)
file_put_contents("mlpayout.txt", date('Y-m-d H:i:s') . " - Incoming: " . json_encode($input) . PHP_EOL, FILE_APPEND);

// Signature Verification
$receivedSign = $input['sign'] ?? null;
if (!$receivedSign) {
    http_response_code(400);
    echo "Missing signature";
    exit;
}

// Remove 'sign' before generating your own
$dataToVerify = $input;
unset($dataToVerify['sign']);

// SORT and GENERATE SIGN
ksort($dataToVerify);
$signString = http_build_query($dataToVerify);
$generatedSign = md5($signString . $secretKey);

// VALIDATE SIGNATURE
if ($generatedSign !== $receivedSign) {
    http_response_code(403);
    echo "Invalid Signature";
    exit;
}

// PROCESS STATUS
$status = (int)$input['status']; // 0 = Pending, 1 = Success, 2 = Failed
$orderCode = $input['merchantCode']; // Your internal order code

// HANDLE STATUS
if ($status === 1) {
    // ✅ Success: Mark success in database
    file_put_contents("mlpayout.txt", "SUCCESS: Order $orderCode marked successful\n", FILE_APPEND);
    // TODO: Update your DB here
} elseif ($status === 2) {
    // ❌ Failed: Mark failed
    file_put_contents("mlpayout.txt", "FAILED: Order $orderCode marked failed\n", FILE_APPEND);
    // TODO: Update your DB here
} else {
    // 🕒 Still pending (optional to handle)
    file_put_contents("mlpayout.txt", "PENDING: Order $orderCode still pending\n", FILE_APPEND);
}

// RETURN RESPONSE TO GATEWAY
echo "success"; // Required by gateway (case-insensitive)

