<?php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Always return JSON wrapper
function json_response($status, $message, $data = []) {
    echo json_encode([
        'status' => $status,
        'message' => $message,
        'data' => $data
    ]);
    exit;
}

// Check if NHIS number provided
if (!isset($_GET['nhis_no'])) {
    json_response(false, 'NHIS number is required');
}

$nhis_no = trim($_GET['nhis_no']);

// Validate NHIS number format (must be 8 digits)
if (!preg_match('/^[0-9]{8}$/', $nhis_no)) {
    json_response(false, 'NHIS number must be exactly 8 digits');
}

// Set up API data
$api_url = "https://nhis.gov.gh/api/verify";

$payload = json_encode([
    "account_id" => "AP1258",
    "client_password" => "b?q5JGlWBc8y3hZomFS26tgrP",
    "nhis_number" => $nhis_no
]);

$curl = curl_init();

curl_setopt_array($curl, [
    CURLOPT_URL => $api_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Content-Length: ' . strlen($payload)
    ],
    CURLOPT_TIMEOUT => 20
]);

$response = curl_exec($curl);

// cURL failure
if ($response === false) {
    json_response(false, 'Connection error: ' . curl_error($curl));
}

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

// HTTP error
if ($http_code !== 200) {
    json_response(false, "API returned HTTP code $http_code");
}

// Decode API response
$api_data = json_decode($response, true);

// Invalid JSON
if ($api_data === null) {
    json_response(false, 'Invalid JSON received from NHIS server');
}

// Validate expected fields
if (
    !isset($api_data['active']) ||
    !isset($api_data['name']) ||
    !isset($api_data['dob']) ||
    !isset($api_data['valid_from']) ||
    !isset($api_data['valid_to'])
) {
    json_response(false, 'Unexpected response structure from NHIS API', $api_data);
}

// If active == false return inactive message
if (!$api_data['active']) {
    json_response(false, 'NHIS card is inactive or expired', $api_data);
}

// SUCCESS RESPONSE
json_response(true, 'NHIS number verified successfully', $api_data);
?>
