<?php
/**
 * Cronjob: Systemstatistiken erfassen (CPU-Temperatur, Stromverbrauch).
 * Läuft jede Minute, speichert in Tabelle "statistiken", löscht Daten älter als 7 Tage.
 * Kann standalone aufgerufen werden: php /var/www/wecker/cronjob/collect_stats.php
 */
$weckerRoot = dirname(__DIR__);
if (!function_exists('function_einstellung_hole')) {
    require $weckerRoot . '/config.php';
    require FUNCTIONS_ROOT . '/functions_db.php';
    require FUNCTIONS_ROOT . '/functions_common.php';
}

$pdo = $GLOBALS['pdo'] ?? null;
if (!$pdo) {
    error_log('[collect_stats] Keine DB-Verbindung.');
    exit(1);
}

// CPU-Temperatur lesen
$cpuTemp = null;
$sysfsPath = '/sys/class/thermal/thermal_zone0/temp';
if (is_readable($sysfsPath)) {
    $raw = (int)trim(file_get_contents($sysfsPath));
    $cpuTemp = round($raw / 1000, 1);
} elseif (PHP_OS_FAMILY === 'Linux') {
    $out = [];
    @exec('vcgencmd measure_temp 2>/dev/null', $out);
    if (!empty($out[0]) && preg_match('/temp=([\d.]+)/', $out[0], $m)) {
        $cpuTemp = (float)$m[1];
    }
}

// Stromverbrauch lesen
$watts = null;
$volt  = null;
$amp   = null;

if (PHP_OS_FAMILY === 'Linux') {
    // Methode 1: Pi 5 – sysfs power_supply CHARGER
    $chargerDir = '/sys/class/power_supply/CHARGER/';
    if (is_dir($chargerDir)) {
        $vRaw = @file_get_contents($chargerDir . 'voltage_now');
        $iRaw = @file_get_contents($chargerDir . 'current_now');
        if ($vRaw !== false && $iRaw !== false) {
            $volt  = round((int)trim($vRaw) / 1000000, 2);
            $amp   = round((int)trim($iRaw) / 1000000, 2);
            $watts = round($volt * $amp, 2);
        }
    }

    // Methode 2: Pi 4 – vcgencmd pmic_read_adc
    if ($watts === null) {
        $out = [];
        @exec('vcgencmd pmic_read_adc 2>/dev/null', $out);
        if (!empty($out)) {
            $extVolt  = null;
            $currents = [];
            foreach ($out as $line) {
                if (preg_match('/EXT5V_V\s+([\d.]+)V?/i', $line, $m)) {
                    $extVolt = (float)$m[1];
                }
                if (preg_match('/(\w+)_I\s+([\d.]+)A?/i', $line, $m)) {
                    $currents[$m[1]] = (float)$m[2];
                }
            }
            if ($extVolt !== null && !empty($currents)) {
                $totalAmp = array_sum($currents);
                $volt     = round($extVolt, 2);
                $amp      = round($totalAmp, 2);
                $watts    = round($volt * $totalAmp, 2);
            }
        }
    }

    // Methode 3: generisch sysfs power_supply
    if ($watts === null) {
        foreach ((array)@glob('/sys/class/power_supply/*/') as $dir) {
            $vRaw = @file_get_contents($dir . 'voltage_now');
            $iRaw = @file_get_contents($dir . 'current_now');
            if ($vRaw !== false && $iRaw !== false && (int)trim($iRaw) > 0) {
                $volt  = round((int)trim($vRaw) / 1000000, 2);
                $amp   = round((int)trim($iRaw) / 1000000, 2);
                $watts = round($volt * $amp, 2);
                break;
            }
        }
    }
}

// Eintrag in DB schreiben
try {
    $stmt = $pdo->prepare(
        'INSERT INTO statistiken (zeitstempel, cpu_temp, watts, volt, amp) VALUES (NOW(), ?, ?, ?, ?)'
    );
    $stmt->execute([$cpuTemp, $watts, $volt, $amp]);
} catch (Throwable $e) {
    error_log('[collect_stats] DB-Insert Fehler: ' . $e->getMessage());
    exit(1);
}

// Alte Daten bereinigen (älter als 7 Tage)
try {
    $pdo->exec("DELETE FROM statistiken WHERE zeitstempel < DATE_SUB(NOW(), INTERVAL 7 DAY)");
} catch (Throwable $e) {
    error_log('[collect_stats] Cleanup Fehler: ' . $e->getMessage());
}
