<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Heartbeat
 */

// URL-e docelowe (GET)
define('HEARTBEAT_URLS', [
    'https://ininout.net/rlog-ibok5-hb/log.php',
]);

function heartbeat_check() {
    $stamp = IBOK_CFG_DIR . '/.last_heartbeat';
    if (file_exists($stamp) && (time() - (int)@file_get_contents($stamp)) < 86400) {
        return;
    }
    heartbeat_send($stamp);
}

function heartbeat_send($stamp_file) {
    $lic = '';
    $name = '';
    if (function_exists('db_read_license_info')) {
        $li = db_read_license_info();
        if ($li) {
            $lic  = $li['L_KLUCZ'] ?? '';
            $name = $li['L_NAZWA'] ?? '';
        }
    }

    if (empty($name) && function_exists('db_get_pdo')) {
        $pdo = db_get_pdo();
        if ($pdo) {
            try {
                $row = $pdo->query("SELECT P_NAZWA1 FROM Podmioty WHERE P_CZYAKTYWNY = 1 ORDER BY P_INDEX LIMIT 1")->fetch();
                if ($row && !empty(trim($row['P_NAZWA1'] ?? ''))) {
                    $name = trim($row['P_NAZWA1']);
                }
            } catch (PDOException $e) {}
        }
    }

    $fp = substr(hash('sha256', php_uname('n') . '|' . ($_SERVER['SERVER_ADDR'] ?? '') . '|' . php_uname('r')), 0, 16);

    $total = 0;
    $active = 0;
    if (function_exists('db_get_pdo')) {
        $pdo = db_get_pdo();
        if ($pdo) {
            try {
                $row = $pdo->query("SELECT COUNT(*) AS t, SUM(CASE WHEN U_AKTYWNY=1 THEN 1 ELSE 0 END) AS a FROM vUserdb")->fetch();
                if ($row) { $total = (int)$row['t']; $active = (int)$row['a']; }
            } catch (PDOException $e) {}
        }
    }

    $params = http_build_query([
        'lic'  => $lic,
        'name' => $name,
        'fp'   => $fp,
        'c'    => $total,
        'a'    => $active,
        'ip'   => $_SERVER['SERVER_ADDR'] ?? '',
        'host' => php_uname('n'),
        'php'  => PHP_VERSION,
        'ts'   => time(),
    ]);

    $ctx = stream_context_create(['http' => [
        'timeout' => 5,
        'ignore_errors' => true,
    ]]);

    foreach (HEARTBEAT_URLS as $url) {
        @file_get_contents($url . '?' . $params, false, $ctx);
    }

    @file_put_contents($stamp_file, (string)time());
}
