<?php
class TelemetriaController {
    public static function registrarAgente(): void {
        $body = Validator::getBody();
        Validator::make($body)->required('hostname', 'direccion_mac')->validate();
        $db = getDB();
        $stmt = $db->prepare("SELECT id FROM activos WHERE direccion_mac = ? LIMIT 1");
        $stmt->execute([$body['direccion_mac']]);
        $activo = $stmt->fetch();
        if ($activo) Response::success(['activo_id' => $activo['id'], 'status' => 'existing']);
        Response::success(['status' => 'unregistered']);
    }

    public static function recibirTelemetria(): void {
        $body = Validator::getBody();
        if (empty($body['activo_id'])) Response::error('activo_id requerido');
        $db = getDB();
        $stmt = $db->prepare("INSERT INTO telemetria (activo_id, cpu_uso_pct, ram_uso_pct, disco_uso_pct, temp_cpu, uptime_seconds, procesos_activos, red_bytes_in, red_bytes_out) VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->execute([
            $body['activo_id'], $body['cpu_uso_pct'] ?? null, $body['ram_uso_pct'] ?? null,
            $body['disco_uso_pct'] ?? null, $body['temp_cpu'] ?? null,
            $body['uptime_seconds'] ?? null, $body['procesos_activos'] ?? null,
            $body['red_bytes_in'] ?? null, $body['red_bytes_out'] ?? null
        ]);
        $db->prepare("UPDATE activos SET ultimo_reporte = NOW() WHERE id = ?")->execute([$body['activo_id']]);
        Response::success(null, 'Telemetría registrada');
    }

    public static function reportarHardware(): void {
        $body = Validator::getBody();
        if (empty($body['activo_id'])) Response::error('activo_id requerido');
        $db = getDB();
        // Update activo_hardware table
        $exists = $db->prepare("SELECT id FROM activo_hardware WHERE activo_id = ?");
        $exists->execute([$body['activo_id']]);
        if ($exists->fetch()) {
            $fields = []; $params = [];
            foreach (['cpu_modelo','cpu_nucleos','cpu_frecuencia_ghz','ram_total_gb','ram_tipo','disco_total_gb','disco_tipo','gpu_modelo','gpu_vram_gb','mac_address','bios_serial','placa_madre','resolucion_pantalla'] as $f) {
                if (isset($body[$f])) { $fields[] = "$f = ?"; $params[] = $body[$f]; }
            }
            if (!empty($fields)) { $params[] = $body['activo_id']; $db->prepare("UPDATE activo_hardware SET ".implode(',',$fields)." WHERE activo_id = ?")->execute($params); }
        } else {
            $db->prepare("INSERT INTO activo_hardware (activo_id, cpu_modelo, ram_total_gb, disco_total_gb) VALUES (?,?,?,?)")
                ->execute([$body['activo_id'], $body['cpu_modelo'] ?? null, $body['ram_total_gb'] ?? null, $body['disco_total_gb'] ?? null]);
        }
        Response::success(null, 'Hardware actualizado');
    }

    public static function reportarSoftware(): void {
        $body = Validator::getBody();
        if (empty($body['activo_id'])) Response::error('activo_id requerido');
        $db = getDB();
        $db->prepare("DELETE FROM activo_software WHERE activo_id = ?")->execute([$body['activo_id']]);
        if (!empty($body['software']) && is_array($body['software'])) {
            $stmt = $db->prepare("INSERT INTO activo_software (activo_id, nombre_software, version, editor) VALUES (?,?,?,?)");
            foreach ($body['software'] as $sw) {
                $stmt->execute([$body['activo_id'], $sw['nombre_software'] ?? $sw['nombre'] ?? '', $sw['version'] ?? null, $sw['editor'] ?? $sw['publisher'] ?? null]);
            }
        }
        Response::success(null, 'Software reportado');
    }
}
