<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/api_client.php';

$config = api_config();
$baseUrl = rtrim((string)$config['base_url'], '');

echo "=== Karvi API Diagnostic ===\n\n";
echo "cURL: " . (api_curl_available() ? 'YES' : 'NO') . "\n";
echo "enabled: " . (api_is_configured() ? 'YES' : 'NO') . "\n";
echo "auth_enabled: " . (api_auth_enabled() ? 'YES' : 'NO') . "\n";
echo "base_url: {$baseUrl}\n\n";

$tests = [
    ['http://karviapi1.de', '/karvipartner/login'],
    ['https://karviapi1.de', '/karvipartner/login'],
    ['http://karviapi1.de', '/api/contracts'],
    ['https://karviapi1.de', '/api/contracts'],
];

foreach ($tests as [$host, $path]) {
    $url = rtrim($host, '/') . $path;
    if (!function_exists('curl_init')) {
        echo "{$url} => curl not available\n";
        continue;
    }

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_NOBODY => $path === '/api/contracts',
        CURLOPT_CUSTOMREQUEST => $path === '/api/contracts' ? 'GET' : 'POST',
        CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/json'],
        CURLOPT_POSTFIELDS => $path === '/karvipartner/login'
            ? json_encode(['email' => 'test@test.com', 'password' => 'test'])
            : null,
    ]);
    $raw = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    $body = is_string($raw) ? substr($raw, 0, 200) : '';
    echo "{$url}\n  HTTP {$status}" . ($err !== '' ? " curl_error={$err}" : '') . "\n  " . ($body !== '' ? $body : '(empty)') . "\n\n";
}

$login = api_auth_login('admin', '123456');
echo "api_auth_login(admin/123456): " . ($login['success'] ? 'OK' : 'FAIL') . "\n";
echo "  message: " . ($login['message'] ?? '') . "\n";
