<?php
// Set response type to JSON
header("Content-Type: application/json");

// 1. Get raw POST body from gateway
$raw = file_get_contents("php://input");

// 2. Optionally log it for debugging
file_put_contents("kilipay_callback_" . date("Y-m-d_H-i-s") . ".log", $raw . PHP_EOL, FILE_APPEND);

// 3. Decode JSON
$data = json_decode($raw, true);

if (!$data || !isset($data['tradeNo'])) {
    // Invalid callback payload
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid callback']);
    exit;
}

// Example structure: log or update DB
$tradeNo       = $data['tradeNo'];
$status        = $data['status'];        // 0000 = success, 0015 = processing, others = failed
$message       = $data['message'] ?? ''; // E.g. "SUCCESS", "FAILED", "TIMEOUT"
$amount        = $data['amount'] ?? '';
$successTime   = $data['successTime'] ?? '';
$kiliTradeNo   = $data['kiliTradeNo'] ?? '';

// 4. Here you would update your database payout record
// Example only:
file_put_contents("payout_status.log", "[$tradeNo] => $status ($message) @ $successTime" . PHP_EOL, FILE_APPEND);

// TODO: You should:
// - Verify status
// - Update your payout DB record
// - Mark transaction as complete/failed

// 5. Respond to gateway
echo json_encode(['status' => 'received', 'tradeNo' => $tradeNo]);
