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

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

// === Step 2: Decode JSON ===
$data = json_decode($raw, true);
if (!$data || !isset($data['transdata'])) {
    file_put_contents('callback_new_debug.txt', "Invalid or missing transdata.\n", FILE_APPEND);
    echo json_encode(['code' => 400, 'message' => 'Invalid data']);
    exit;
}

$transdata = $data['transdata'];

// === Step 3: Extract Needed Fields ===
$txn_id = $transdata['order_no'] ?? '';
$status = strtolower($transdata['order_status'] ?? '');
$gateway_ref = $transdata['plat_order_no'] ?? '';
$amount = $transdata['order_amount'] ?? '';
$sign   = $data['sign'] ?? '';  // Optional — not verifying yet

if ($status !== 'success' || !$txn_id) {
    file_put_contents('callback_new_debug.txt', "Non-success or missing txn_id.\n", FILE_APPEND);
    echo "success"; // Still respond to stop retries
    exit;
}

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

if (!$txn) {
    file_put_contents('callback_new_log.txt', "Transaction not found or already processed: $txn_id\n", FILE_APPEND);
    echo "success";
    exit;
}

$user_id = $txn['user_id'];
$final_amount = $txn['amount'];

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

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

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

// ✅ Merchant webhook
$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 POST 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_new_log.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);
}

// ✅ Final response
echo "success";
exit;
