<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/app/bootstrap.php';

$hospital = isset($_GET['hospital']) ? strtolower((string)$_GET['hospital']) : 'njch';

header('Content-Type: text/plain; charset=utf-8');

echo "Oracle connection test\n";
echo "Hospital: " . $hospital . "\n";
echo "PDO OCI available: " . (in_array('oci', PDO::getAvailableDrivers(), true) ? 'YES' : 'NO') . "\n\n";

$config = config('hospitals.' . $hospital . '.database');
if (!$config) {
    echo "ERROR: Hospital config not found.\n";
    exit;
}

echo "connect_type: " . ($config['connect_type'] ?? '') . "\n";
echo "tns: " . ($config['tns'] ?? '') . "\n";
echo "host: " . ($config['host'] ?? '') . "\n";
echo "port: " . ($config['port'] ?? '') . "\n";
echo "service: " . ($config['service'] ?? '') . "\n";
echo "sid: " . ($config['sid'] ?? '') . "\n";
echo "username: " . ($config['username'] ?? '') . "\n\n";

if (!empty($config['host']) && !empty($config['port'])) {
    echo "TCP test: ";
    $errno = 0;
    $errstr = '';
    $fp = @fsockopen((string)$config['host'], (int)$config['port'], $errno, $errstr, 5);
    if ($fp) {
        fclose($fp);
        echo "OK\n";
    } else {
        echo "FAILED ($errno) $errstr\n";
    }
}

echo "\nDatabase test: ";
try {
    $row = \App\Core\Database::fetchOne($hospital, 'SELECT SYSDATE AS server_date FROM dual');
    echo "SUCCESS\n";
    echo "SERVER_DATE: " . ($row['server_date'] ?? '') . "\n";
} catch (Throwable $e) {
    echo "FAILED\n";
    echo $e->getMessage() . "\n";
}
