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

file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Starting manual callback process\n", FILE_APPEND);

// Only take successful, not-yet-sent transactions
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE status = 'success' AND webhook_sent = 0");
$stmt->execute();
$transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($transactions as $txn) {
    $txn_id   = $txn['txn_id'];
    $user_id  = $txn['user_id'];
    $amount   = $txn['amount'];
    $reference = $txn['reference'];

    file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Processing txn_id: $txn_id for user_id: $user_id\n", FILE_APPEND);

    // Get webhook URL and key
    $stmtUser = $pdo->prepare("SELECT webhook_url, merchant_key FROM users WHERE id = ?");
    $stmtUser->execute([$user_id]);
    $user = $stmtUser->fetch();

    if (empty($user['webhook_url']) || empty($user['merchant_key'])) {
        file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Missing webhook_url or merchant_key for user_id $user_id\n", FILE_APPEND);
        continue;
    }

    $webhook_url = $user['webhook_url'];
    $merchant_key = $user['merchant_key'];

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

    // Sign payload
    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);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    // Log webhook response
    file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Sent to: $webhook_url | txn_id: $txn_id | Payload: " . json_encode($webhook_data) . " | Response: $response | Error: $error\n", FILE_APPEND);

    // If webhook success (optional: you can check $response == 'ok')
    if (strpos(strtolower($response), 'ok') !== false) {
        // Mark as sent
        $update = $pdo->prepare("UPDATE transactions SET webhook_sent = 1 WHERE txn_id = ?");
        $update->execute([$txn_id]);
    } else {
        file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Webhook failed for txn_id $txn_id\n", FILE_APPEND);
    }
}

file_put_contents('manual_callback_log.txt', date('Y-m-d H:i:s') . " - Manual callback process completed.\n", FILE_APPEND);

echo "Manual callback sent.";
?>
