<?php
/**
 * test_maxim_json.php — same probe as before, but the script's own
 * output is JSON (not plain text), so it's easy to pipe, parse, or
 * log elsewhere. Not for cron — diagnostic only.
 *
 * Run: php test_maxim_json.php
 */

$url      = 'https://admin.porihoquecyber.com/apimaxim';
$username = 'mxP0r1apiUsr';   // <-- put real API username here
$password = 'mRwDCacl#25640GyBUfLMs'; // <-- put real API password here
$apitype  = '6'; // change to test 3,4,5,6,7

$payload = [
    'username' => $username,
    'password' => $password,
    'apitype'  => $apitype,
];

$json = json_encode($payload);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $json,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json),
    ],
    CURLOPT_TIMEOUT        => 20,
    CURLOPT_SSL_VERIFYPEER => true,
]);

$rawResponse = curl_exec($ch);
$httpCode    = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErrno   = curl_errno($ch);
$curlErr     = curl_error($ch);
curl_close($ch);

// Try to decode the API's own response body as JSON, if there is one.
$apiBody = null;
$apiBodyIsJson = false;
if ($rawResponse !== false && $rawResponse !== '') {
    $decoded = json_decode($rawResponse, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $apiBody = $decoded;
        $apiBodyIsJson = true;
    }
}

$result = [
    'request' => [
        'url'     => $url,
        'apitype' => $apitype,
        'body'    => $payload, // password included since this is local diagnostic output, not shipped anywhere
    ],
    'transport' => [
        'http_status'    => $httpCode ?: null,
        'curl_errno'     => $curlErrno ?: null,
        'curl_error'     => $curlErr ?: null,
        'reached_server' => $rawResponse !== false,
    ],
    'response' => [
        'raw'     => $rawResponse === false ? null : $rawResponse,
        'is_json' => $apiBodyIsJson,
        'parsed'  => $apiBody,
    ],
    'verdict' => null,
];

// ---- Build a verdict string, same logic as before, now as a field ----

if ($rawResponse === false) {
    $result['verdict'] = 'network_error';
} elseif ($httpCode !== 200) {
    $result['verdict'] = 'server_level_error_non_200';
} elseif (!$apiBodyIsJson) {
    $result['verdict'] = 'http_200_but_invalid_json';
} else {
    $errorCode = $apiBody['Error_Code'] ?? null;
    $verdictMap = [
        '200' => 'success',
        '401' => 'auth_failed',
        '409' => 'ip_not_allowed',
        '406' => 'missing_field',
        '410' => 'no_data',
        '500' => 'server_error',
    ];
    $result['verdict'] = $verdictMap[$errorCode] ?? 'unrecognised_error_code';
}

echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
?>