<?php
// lib/Monitor.php - ИСПРАВЛЕННАЯ ВЕРСИЯ
class Monitor {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    public function checkSystemHealth() {
        return [
            'database' => $this->checkDatabase(),
            'data_freshness' => $this->checkDataFreshness(),
            'disk_space' => $this->checkDiskSpace(),
            'system_time' => $this->checkSystemTime(),
            'recent_activity' => $this->checkRecentActivity()
        ];
    }
    
    private function checkDatabase() {
        try {
            $stmt = $this->pdo->query("SELECT COUNT(*) as count FROM readings");
            $result = $stmt->fetch();
            $count = $result['count'] ?? 0;
            
            return [
                'status' => 'healthy', 
                'message' => 'Database connection OK',
                'records_count' => $count
            ];
        } catch (Exception $e) {
            Logger::error('Database health check failed', ['error' => $e->getMessage()]);
            return [
                'status' => 'error', 
                'message' => $e->getMessage()
            ];
        }
    }
    
    private function checkDataFreshness() {
        try {
            $stmt = $this->pdo->query("
                SELECT 
                    TIMESTAMPDIFF(MINUTE, MAX(timestamp), NOW()) as minutes_ago,
                    COUNT(*) as total_records
                FROM readings
            ");
            $result = $stmt->fetch();
            
            $minutes_ago = $result['minutes_ago'] ?? 999;
            $total_records = $result['total_records'] ?? 0;
            
            if ($total_records === 0) {
                return [
                    'status' => 'warning', 
                    'message' => 'No data records found',
                    'minutes_ago' => $minutes_ago
                ];
            }
            
            if ($minutes_ago < 65) {
                return [
                    'status' => 'fresh', 
                    'message' => 'Data is up to date',
                    'minutes_ago' => $minutes_ago
                ];
            } else {
                Logger::warning('Data freshness check', ['minutes_ago' => $minutes_ago]);
                return [
                    'status' => 'stale', 
                    'message' => 'Data is outdated',
                    'minutes_ago' => $minutes_ago
                ];
            }
        } catch (Exception $e) {
            return [
                'status' => 'error', 
                'message' => 'Check failed: ' . $e->getMessage()
            ];
        }
    }
    
    private function checkDiskSpace() {
        $free = disk_free_space(__DIR__);
        $total = disk_total_space(__DIR__);
        
        if ($total === false) {
            return [
                'status' => 'unknown',
                'message' => 'Could not determine disk space'
            ];
        }
        
        $percent_free = ($free / $total) * 100;
        $free_gb = round($free / (1024*1024*1024), 2);
        
        $status = $percent_free > 20 ? 'healthy' : ($percent_free > 10 ? 'warning' : 'critical');
        
        return [
            'free_gb' => $free_gb,
            'percent_free' => round($percent_free, 1),
            'status' => $status,
            'message' => "{$free_gb} GB free ({$percent_free}%)"
        ];
    }
    
    private function checkSystemTime() {
        return [
            'server_time' => date('Y-m-d H:i:s'),
            'timezone' => date_default_timezone_get(),
            'status' => 'healthy'
        ];
    }
    
    private function checkRecentActivity() {
        try {
            $stmt = $this->pdo->query("
                SELECT 
                    COUNT(*) as last_hour,
                    AVG(security_index) as avg_index
                FROM readings 
                WHERE timestamp >= DATE_SUB(NOW(), INTERVAL 1 HOUR)
            ");
            $result = $stmt->fetch();
            
            return [
                'records_last_hour' => $result['last_hour'] ?? 0,
                'average_index' => round($result['avg_index'] ?? 0, 2),
                'status' => 'healthy'
            ];
        } catch (Exception $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage()
            ];
        }
    }
}
?>