<?php
/**
 * test_webhook.php
 * Public API endpoint (see /api/test-webhook in root .htaccess). Lets a
 * developer trigger a test webhook delivery to their configured URL via
 * API, same as the "Test Webhook" button in the admin panel does.
 */
define('PROJECT_ROOT', realpath(dirname(__FILE__)) . '/../');
include PROJECT_ROOT . 'pages/dbFunctions.php';
include PROJECT_ROOT . 'pages/dbInfo.php';
include PROJECT_ROOT . 'auth/config.php';
include PROJECT_ROOT . 'includes/webhook_lib.php';

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}
header("Content-Type: application/json");

$userToken = $_POST['user_token'] ?? '';
if ($userToken === '') {
    echo json_encode(["status" => false, "message" => "user_token is required"]);
    exit;
}

$userRes = mysqli_query($conn, "SELECT id, callback_url FROM users WHERE user_token = '" . mysqli_real_escape_string($conn, $userToken) . "' LIMIT 1");
if (!$userRes || mysqli_num_rows($userRes) === 0) {
    echo json_encode(["status" => false, "message" => "Invalid user_token"]);
    exit;
}
$user = mysqli_fetch_assoc($userRes);

if (empty($user['callback_url'])) {
    echo json_encode(["status" => false, "message" => "No webhook URL configured for this account yet."]);
    exit;
}

$result = send_test_webhook($conn, (int)$user['id'], $user['callback_url']);

echo json_encode([
    "status"    => $result['ok'],
    "message"   => $result['ok'] ? "Test webhook delivered successfully" : "Webhook delivery failed",
    "http_code" => $result['http_code'],
    "response"  => $result['response'],
]);
