<?php
require '../includes/db.php';
header("Content-Type: application/json");

// ✅ KiliPay secret key for verifying signature
define('KILIPAY_SECRET', '4b46ecb8294b47f48bc2dc237afe2680');

// ✅ Step 1: Read raw input and log it
$raw = file_get_contents('php://input');
file_put_contents('callback_debug.txt', date('Y-m-d H:i:s') . " - Raw input: $raw\n\n", FILE_APPEND);

// ✅ Step 2: Decode JSON
$data = json_decode($raw, true);
if (!$data) {
    file_put_contents('callback_debug.txt', date('Y-m-d H:i:s') . " - JSON decode failed.\n\n", FILE_APPEND);
    echo json_encode(['code' => 400, 'message' => 'Invalid JSON']);
    exit;
}

// ✅ Step 3: Extract required fields
$status        = $data['status'] ?? '';
$txn_id        = $data['tradeNo'] ?? '';
$kiliTradeNo   = $data['kiliTradeNo'] ?? '';
$amount        = $data['amount'] ?? '';
$sign          = $data['sign'] ?? '';
$paymentType   = $data['paymentType'] ?? '';
$successTime   = $data['successTime'] ?? null;

// ✅ Step 4: Verify Signature
$verify_data = $data;
unset($verify_data['sign']);
ksort($verify_data);

$sign_string = '';
foreach ($verify_data as $key => $value) {
    if (!empty($value)) {
        $sign_string .= $key . '=' . (is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : $value);
    }
}
$sign_string .= KILIPAY_SECRET;
$generated_sign = strtolower(md5($sign_string));

if (strtolower($sign) !== $generated_sign) {
    file_put_contents('callback_log.txt', "Signature mismatch\nExpected: $generated_sign\nReceived: $sign\n\n", FILE_APPEND);
    echo json_encode(['code' => 401, 'message' => 'Invalid signature']);
    exit;
}

// ✅ Step 5: Only process if status is "0000" (success)
if ($status === '0000') {
    // 🔍 Lookup the transaction
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ? AND status = 'pending'");
    $stmt->execute([$txn_id]);
    $txn = $stmt->fetch();

    if ($txn) {
        $user_id = $txn['user_id'];
        $final_amount = $txn['amount'];

        // ✅ Update transaction status
        $stmt = $pdo->prepare("UPDATE transactions SET status = 'success', webhook_sent = 1, reference = ?, updated_at = NOW() WHERE txn_id = ?");
        $stmt->execute([$kiliTradeNo, $txn_id]);

        // ✅ Update user balance
        $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
        $stmt->execute([$final_amount, $user_id]);

        // ✅ Update payin request
        $stmt = $pdo->prepare("UPDATE payin_requests SET status = 'approved' WHERE user_id = ? AND txn_id = ?");
        $stmt->execute([$user_id, $txn_id]);

        // ✅ Send webhook to merchant site
        $stmt = $pdo->prepare("SELECT webhook_url, merchant_key FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();

        if (!empty($user['webhook_url']) && !empty($user['merchant_key'])) {
            $webhook_url = $user['webhook_url'];
            $merchant_key = $user['merchant_key'];

            $webhook_data = [
                "txn_id" => $txn_id,
                "status" => "success",
                "amount" => $final_amount,
                "order_sn" => $txn_id
            ];

            // ✅ Generate webhook signature
            ksort($webhook_data);
            $sign_string = '';
            foreach ($webhook_data as $k => $v) {
                $sign_string .= "$k=$v&";
            }
            $sign_string .= "key=" . $merchant_key;
            $webhook_data['sign'] = strtoupper(md5($sign_string));

            // ✅ Send webhook
            $ch = curl_init($webhook_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($webhook_data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $webhook_response = curl_exec($ch);
            $webhook_error = curl_error($ch);
            curl_close($ch);

            // ✅ Log webhook
            file_put_contents('webhook_logk.txt', date('Y-m-d H:i:s') . " - Sent to: $webhook_url\nPayload: " . json_encode($webhook_data) . "\nResponse: $webhook_response\nError: $webhook_error\n\n", FILE_APPEND);
        }

        // ✅ Respond to KiliPay to stop retries
        echo "OK";
        exit;
    } else {
        file_put_contents('callback_log.txt', "Transaction not found or already updated: $txn_id\n", FILE_APPEND);
    }
} else {
    // Log failed/in-process status
    file_put_contents('callback_log.txt', "Non-success status: $status for txn_id: $txn_id\n", FILE_APPEND);
}

// ✅ Always respond OK to prevent retries (even for unhandled cases)
echo "OK";
exit;
