<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$hosts = array('108.167.177.1', 'rrbteam.biz', 'localhost');
$port  = 3306;
$results = array();

foreach ($hosts as $host) {
    // TCP test
    $fp = @fsockopen($host, $port, $errno, $errstr, 5);
    if ($fp) {
        fclose($fp);
        $tcp = 'OPEN';
    } else {
        $tcp = 'CLOSED: ' . $errstr;
    }

    // PDO test
    $pdo_result = 'not tested';
    if ($tcp === 'OPEN' || $host === 'localhost') {
        try {
            $pdo = new PDO(
                "mysql:host=$host;dbname=xrrbteam_rrb26;charset=utf8mb4",
                'xrrbteam_mikes5',
                'Mikel123*',
                array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5)
            );
            $r = $pdo->query("SELECT COUNT(*) as cnt FROM transacciones")->fetch();
            $pdo_result = 'CONNECTED - transacciones: ' . $r['cnt'];
        } catch (Exception $e) {
            $pdo_result = 'FAILED: ' . $e->getMessage();
        }
    }

    $results[$host] = array('tcp' => $tcp, 'pdo' => $pdo_result);
}

// Server's own IP
$myIp = @file_get_contents('https://api.ipify.org', false, stream_context_create(array(
    'http' => array('timeout' => 5)
)));

echo json_encode(array(
    'server_ip' => $myIp ?: 'unknown',
    'tests'     => $results,
), JSON_PRETTY_PRINT);
