<?php
/**
 * Verzi Healthcare Data API — PHP example.
 *
 * Fetches hospitals in California, iterates the paginated results,
 * and screens each hospital's NPI against OIG exclusions. Real,
 * working code — copy-paste and run after setting VERZI_API_KEY.
 *
 * Requires: PHP 8+ (stdlib only; no Composer, no ext-curl)
 *
 * Get a free API key: https://api.healthcaredata.io/signup
 * Full API reference:  https://api.healthcaredata.io/docs
 */

$apiKey = getenv('VERZI_API_KEY');
if (!$apiKey) {
    fwrite(STDERR, "Set VERZI_API_KEY in your environment\n");
    exit(1);
}

const BASE_URL = 'https://api.healthcaredata.io';

function requestJson(string $path, string $apiKey, array $query = []): array {
    $url = BASE_URL . $path;
    if ($query) {
        $url .= '?' . http_build_query($query);
    }
    $ctx = stream_context_create([
        'http' => [
            'method'        => 'GET',
            'header'        => "X-API-Key: $apiKey\r\nAccept: application/json\r\n",
            'timeout'       => 30,
            'ignore_errors' => true,
        ],
    ]);
    $body = @file_get_contents($url, false, $ctx);
    $status = 0;
    foreach ($http_response_header ?? [] as $h) {
        if (preg_match('#^HTTP/\S+\s+(\d+)#', $h, $m)) {
            $status = (int)$m[1];
        }
    }
    if ($status === 401) throw new RuntimeException('Invalid API key');
    if ($status === 429) throw new RuntimeException('Rate limited — upgrade at /pricing');
    if ($status >= 400) throw new RuntimeException("HTTP $status: $body");
    return json_decode($body, true);
}

function searchHospitals(string $apiKey, string $state, int $pageSize = 100): array {
    $all = [];
    $offset = 0;
    while (true) {
        $data = requestJson('/hospitals', $apiKey, [
            'state' => $state,
            'limit' => $pageSize,
            'offset' => $offset,
        ]);
        $results = $data['results'] ?? [];
        if (empty($results)) break;
        $all = array_merge($all, $results);
        if (count($results) < $pageSize) break;
        $offset += $pageSize;
    }
    return $all;
}

function checkExclusion(string $apiKey, string $npi): bool {
    $data = requestJson("/exclusions/check/$npi", $apiKey);
    return (bool)($data['excluded'] ?? false);
}

$hospitals = searchHospitals($apiKey, 'CA');
printf("Found %d California hospitals\n", count($hospitals));
foreach (array_slice($hospitals, 0, 5) as $h) {
    $stars = $h['overall_rating'] ?? 'unrated';
    printf("  %s  %-50s  %s*\n", $h['ccn'], $h['name'], $stars);
}
