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

require '../includes/db.php'; // PDO connection file

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

// Get txn_id from GET or POST
$txn_id = $_REQUEST['txn_id'] ?? null;
if (!$txn_id) {
    echo json_encode(['status' => 'fail', 'message' => 'txn_id required']);
    exit;
}

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

if (!$txn) {
    echo json_encode(['status' => 'fail', 'message' => 'No success transaction found']);
    exit;
}

// Fetch user webhook info
$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'])) {
    echo json_encode(['status' => 'fail', 'message' => 'User webhook info missing']);
    exit;
}

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

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

// Send webhook via CURL
$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);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);

if ($http_code == 200) {
    // Update webhook_sent flag to 1
    $stmt = $pdo->prepare("UPDATE transactions SET webhook_sent = 1 WHERE txn_id = ?");
    $stmt->execute([$txn_id]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Webhook resent successfully',
        'response' => $response
    ]);
} else {
    echo json_encode([
        'status' => 'fail',
        'message' => 'Webhook resend failed',
        'http_code' => $http_code,
        'curl_error' => $curl_error,
        'response' => $response,
    ]);
}
?>
