<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require '../includes/db.php';

function logCallback($msg) {
    file_put_contents("callback_logm.txt", date("Y-m-d H:i:s") . " - $msg\n", FILE_APPEND);
}

header("Content-Type: application/json");

define('SECRET_KEY', 'b208669f0d6fc2e262786a8a523a61bc');

// Step 1: Get input and decode
$inputJSON = file_get_contents('php://input');
$inputData = json_decode($inputJSON, true);

if (!$inputData || !isset($inputData['transdata']) || !isset($inputData['sign'])) {
    logCallback("Invalid callback structure: $inputJSON");
    echo json_encode(['message' => 'fail', 'reason' => 'Invalid structure']);
    exit;
}

// Decode transdata (urlencoded JSON string)
$transdata_raw = urldecode($inputData['transdata']);
$transdata = json_decode($transdata_raw, true);

if (!$transdata) {
    logCallback("Failed to parse transdata: " . $inputData['transdata']);
    echo json_encode(['message' => 'fail', 'reason' => 'Invalid transdata']);
    exit;
}

// Merge for signature verification
$data = $transdata;
$data['sign'] = $inputData['sign'];

logCallback("Parsed callback data: " . json_encode($data));

// Step 2: Signature verify
$verify_data = $transdata; // only transdata part, not "sign"
ksort($verify_data);
$sign_str = '';
foreach ($verify_data as $k => $v) {
    if ($v !== '') {
        $sign_str .= "$k=$v&";
    }
}
$sign_str .= "key=" . SECRET_KEY;
$generated_sign = strtoupper(md5($sign_str));

if ($generated_sign !== strtoupper($data['sign'])) {
    logCallback("Signature mismatch. Generated: $generated_sign, Received: " . $data['sign']);
    echo json_encode(['message' => 'fail', 'reason' => 'Signature mismatch']);
    exit;
}

// Step 3: Handle payment success
$txn_id = $data['order_no'];
$order_amount = floatval($data['order_amount'] ?? 0);
$status_text = $data['payment'] ?? '';
$status_lower = strtolower($status_text);

// Accept if contains any "success" keyword (Chinese or English)
if (
    strpos($status_text, '成功') === false &&  // Chinese (成功, 支付成功, etc.)
    strpos($status_lower, 'success') === false && // English
    strpos($status_lower, 'completed') === false
) {
    logCallback("Payment not successful: $status_text");
    echo json_encode(['message' => 'fail', 'reason' => 'Payment not marked as success']);
    exit;
}



// Step 4: Find and update transaction
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ? AND status = 'pending'");
$stmt->execute([$txn_id]);
$txn = $stmt->fetch();

if (!$txn) {
    logCallback("No pending transaction found for txn_id: $txn_id");
    echo json_encode(['message' => 'success', 'reason' => 'No matching txn']);
    exit;
}

try {
    $pdo->beginTransaction();

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

    // Update payin request
    $stmt = $pdo->prepare("UPDATE payin_requests SET status = 'approved' WHERE user_id = ? AND txn_id = ?");
    $stmt->execute([$txn['user_id'], $txn_id]);
    
    logCallback("payin_requests update affected rows: " . $stmt->rowCount());


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

    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    logCallback("DB error: " . $e->getMessage());
    echo json_encode(['message' => 'fail', 'reason' => 'DB error']);
    exit;
}

// Step 5: Webhook to user
$stmt = $pdo->prepare("SELECT webhook_url, merchant_key FROM users WHERE id = ?");
$stmt->execute([$txn['user_id']]);
$user = $stmt->fetch();

if (!empty($user['webhook_url']) && !empty($user['merchant_key'])) {
    $webhook_data = [
        "txn_id" => $txn_id,
        "status" => "success",
        "amount" => $txn['amount'],
        "order_sn" => $txn_id,
    ];

    ksort($webhook_data);
    $sign_str = '';
    foreach ($webhook_data as $k => $v) {
        $sign_str .= "$k=$v&";
    }
    $sign_str .= "key=" . $user['merchant_key'];
    $webhook_data['sign'] = strtoupper(md5($sign_str));

    file_put_contents("webhook_user_logm.txt", date("Y-m-d H:i:s") . " - Sending webhook to: " . $user['webhook_url'] . "\nPayload: " . json_encode($webhook_data) . "\n", FILE_APPEND);

    $ch = curl_init($user['webhook_url']);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($webhook_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    file_put_contents("webhook_user_logm.txt", date("Y-m-d H:i:s") . " - Webhook response: HTTP $http_code, Response: $response, Error: $error\n\n", FILE_APPEND);
}

echo json_encode(['message' => 'success']);
exit;
