<?php
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireLogin();
csrfVerify();

$user = getUserById($_SESSION['user_id']);
$webhookUrl = trim($user['webhook_url'] ?? '');

if (empty($webhookUrl)) {
    jsonResponse(['status' => 'error', 'message' => 'No webhook URL configured.'], 400);
}

// Ensure the URL is valid
if (!filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
    jsonResponse(['status' => 'error', 'message' => 'Configured webhook URL is invalid.'], 400);
}

// Build dummy payload
$payload = json_encode([
    'event'          => 'payment.success',
    'order_id'       => 'TEST-' . strtoupper(uniqid()),
    'amount'         => '100.00',
    'payable_amount' => '100.00',
    'status'         => 'success',
    'transaction_id' => 'TEST_TXN_' . strtoupper(uniqid()),
    'utr'            => (string)mt_rand(100000000000, 999999999999),
    'sender_name'    => 'FamGateway Tester',
    'payment_time'   => date('d-m-Y H:i:s'),
    'timestamp'      => time(),
    'is_test'        => true
]);

// Sign payload
$apiKey = $user['api_keys'][0]['key'] ?? '';
$signature = hash_hmac('sha256', $payload, $apiKey);

// Send POST request
$ch = curl_init($webhookUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'X-FamGateway-Signature: ' . $signature,
        'X-FamGateway-Event: payment.success'
    ],
    CURLOPT_SSL_VERIFYPEER => true
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    saveWebhookLog($user['id'], $webhookUrl, $payload, 0, "cURL Error: " . $error);
    jsonResponse(['status' => 'error', 'message' => "Failed to reach webhook: " . $error], 400);
}

saveWebhookLog($user['id'], $webhookUrl, $payload, $httpCode, $response);

if ($httpCode >= 200 && $httpCode < 300) {
    jsonResponse(['status' => 'success', 'message' => "Success! Webhook responded with HTTP $httpCode."], 200);
} else {
    jsonResponse(['status' => 'error', 'message' => "Webhook failed. Server responded with HTTP $httpCode."], 400);
}
