<?php
/**
 * Quick test to see what the Caterpoint API actually returns
 */

// Find autoloader
$autoloadPaths = [
    __DIR__ . '/../../vendor/autoload.php',
    __DIR__ . '/../../NGauge_Base/vendor/autoload.php',
];

foreach ($autoloadPaths as $path) {
    if (file_exists($path)) {
        require_once $path;
        break;
    }
}

// Get collinsfresh params to retrieve API credentials
$paramsPath = __DIR__ . '/../../collinsfresh/common/config/params-local.php';
if (!file_exists($paramsPath)) {
    die("Error: Cannot find params-local.php at: {$paramsPath}\n");
}

$params = require $paramsPath;
$caterpointConfig = $params['caterpoint'] ?? [];

if (empty($caterpointConfig['apiEndpoint']) || empty($caterpointConfig['apiToken'])) {
    die("Error: Caterpoint API endpoint and token not configured in params-local.php\n");
}

echo "Testing Caterpoint API...\n";
echo "Endpoint: {$caterpointConfig['apiEndpoint']}\n";
echo "Token: " . substr($caterpointConfig['apiToken'], 0, 10) . "...\n\n";

// Make raw HTTP request
$url = rtrim($caterpointConfig['apiEndpoint'], '/') . '/api/integration/distributor/orders?limit=1';
echo "Request URL: {$url}\n\n";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $caterpointConfig['apiToken'],
        'Accept: application/xml, text/xml, application/json',
    ],
    CURLOPT_TIMEOUT => 30,
]);

$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURL_INFO_HEADER_SIZE);
curl_close($ch);

if ($curlError) {
    die("CURL Error: {$curlError}\n");
}

$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);

echo "HTTP Status: {$httpCode}\n\n";
echo "Response Headers:\n";
echo $headers . "\n";
echo "\nResponse Body (first 2000 chars):\n";
echo str_repeat('=', 80) . "\n";
echo substr($body, 0, 2000) . "\n";
echo str_repeat('=', 80) . "\n";

// Try to detect format
$trimmed = trim($body);
if (str_starts_with($trimmed, '<?xml') || (str_starts_with($trimmed, '<') && !str_starts_with(strtolower($trimmed), '<!doctype html') && !str_starts_with(strtolower($trimmed), '<html'))) {
    echo "\nDetected format: XML\n";
} elseif (str_starts_with($trimmed, '{') || str_starts_with($trimmed, '[')) {
    echo "\nDetected format: JSON\n";
} elseif (str_starts_with(strtolower(($trimmed)), '<!doctype html') || str_starts_with(strtolower($trimmed), '<html')) {
    echo "\nDetected format: HTML\n";
} else {
    echo "\nDetected format: UNKNOWN\n";
}
