<?php
/**
 * API: System-Info für Einstellungen (IP, letzter Cron-Lauf, Status).
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_common.php';

header('Content-Type: application/json; charset=utf-8');

$storageRoot = defined('STORAGE_ROOT') ? rtrim(STORAGE_ROOT, DIRECTORY_SEPARATOR) : (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'storage');
$stateFile = $storageRoot . DIRECTORY_SEPARATOR . 'cronjob_master.json';

$ip = isset($_SERVER['SERVER_ADDR']) ? trim((string) $_SERVER['SERVER_ADDR']) : '';
if ($ip === '' && function_exists('gethostname')) {
    $host = gethostname();
    if ($host && function_exists('gethostbyname')) {
        $resolved = gethostbyname($host);
        if ($resolved !== $host) {
            $ip = $resolved;
        }
    }
}

$cronLastActivity = null;
$cronStatus = 'error'; // kein Lauf / älter als 5 Min = rot
if (is_file($stateFile)) {
    $content = @file_get_contents($stateFile);
    if ($content !== false) {
        $state = @json_decode($content, true);
        if (is_array($state) && !empty($state['last_activity'])) {
            $cronLastActivity = $state['last_activity'];
            $ts = strtotime($cronLastActivity);
            if ($ts !== false) {
                $age = time() - $ts;
                if ($age <= 60) {
                    $cronStatus = 'ok';   // ≤ 1 Min = grün
                } elseif ($age <= 300) {
                    $cronStatus = 'warn'; // 1–5 Min = gelb
                }
                // > 5 Min bleibt 'error' (rot)
            }
        }
    }
}

function_json_antwort(true, [
    'ip'                 => $ip,
    'cron_last_activity' => $cronLastActivity,
    'cron_status'        => $cronStatus,
]);
