<?php
// CONFIG
define('SECRET_KEY', 'b208669f0d6fc2e262786a8a523a61bc'); // CowPay gateway secret
require '../includes/db.php'; // your DB connection

// 🔧 MODIFY THIS: Transaction ID to simulate
$txn_id = '202508131755083219656361';  // Replace with actual txn_id

// Fetch transaction
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ?");
$stmt->execute([$txn_id]);
$txn = $stmt->fetch();

if (!$txn) {
    exit("❌ Transaction not found.\n");
}

if ($txn['status'] === 'success') {
    echo "✅ Transaction already marked as success. Webhook will be re-fired.\n";
} else {
    echo "ℹ️ Marking transaction as success...\n";

    $pdo->beginTransaction();

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

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

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

    $pdo->commit();
    echo "✅ Transaction updated successfully.\n";
}

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

if (!$user || empty($user['webhook_url'])) {
    exit("❌ No webhook URL configured for this user.\n");
}

// Prepare webhook payload
$webhook_data = [
    "txn_id" => $txn_id,
    "status" => "success",
    "amount" => $txn['amount'],
    "order_sn" => $txn_id,
];

// Sign webhook
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));

// Send webhook
echo "📡 Sending webhook to user: {$user['webhook_url']}...\n";

$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);

// Log webhook
file_put_contents("webhook_user_logm.txt", date("Y-m-d H:i:s") . " - [Manual Trigger] Sent webhook to {$user['webhook_url']}\nPayload: " . json_encode($webhook_data) . "\nResponse: $response\nHTTP Code: $http_code\nCurl Error: $error\n\n", FILE_APPEND);

// Output result
echo "📦 Response from user webhook:\n$response\n";
echo "🔢 HTTP Status: $http_code\n";
if ($error) {
    echo "❗ cURL Error: $error\n";
}
