<?php
class SystemHealthController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();

        $health = [
            'php_version' => phpversion(),
            'mysql_version' => $db->fetchColumn("SELECT VERSION()"),
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'memory_usage' => round(memory_get_usage(true) / 1024 / 1024, 2) . ' MB',
            'memory_limit' => ini_get('memory_limit'),
            'max_upload' => ini_get('upload_max_filesize'),
            'max_post' => ini_get('post_max_size'),
            'timezone' => date_default_timezone_get(),
            'disk_free' => round(disk_free_space(ROOT_PATH) / 1024 / 1024 / 1024, 2) . ' GB',
            'disk_total' => round(disk_total_space(ROOT_PATH) / 1024 / 1024 / 1024, 2) . ' GB',
            'active_sessions' => (int)$db->fetchColumn("SELECT COUNT(*) FROM auth_sessions WHERE is_active = 1"),
            'active_users' => (int)$db->fetchColumn("SELECT COUNT(*) FROM auth_users WHERE is_active = 1 AND is_deleted = 0"),
            'total_members' => (int)$db->fetchColumn("SELECT COUNT(*) FROM members WHERE is_deleted = 0"),
            'active_members' => (int)$db->fetchColumn("SELECT COUNT(*) FROM members WHERE status = 'active' AND is_deleted = 0"),
            'errors_today' => (int)$db->fetchColumn("SELECT COUNT(*) FROM system_error_log WHERE DATE(created_at) = CURDATE()"),
            'open_dq_issues' => (int)$db->fetchColumn("SELECT COUNT(*) FROM data_quality_issues WHERE status = 'open'"),
            'pending_notifications' => (int)$db->fetchColumn("SELECT COUNT(*) FROM notification_queue WHERE status = 'queued'"),
        ];

        $recentErrors = $db->fetchAll("SELECT * FROM system_error_log ORDER BY created_at DESC LIMIT 20");

        $storagePath = ROOT_PATH . '/storage';
        $uploadsPath = ROOT_PATH . '/public/uploads';
        $storageSize = 0;
        if (is_dir($storagePath)) {
            $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($storagePath, \RecursiveDirectoryIterator::SKIP_DOTS));
            foreach ($iterator as $file) { $storageSize += $file->getSize(); }
        }
        $health['storage_used'] = round($storageSize / 1024 / 1024, 2) . ' MB';

        $this->view('system-health/index', [
            'title' => lang('admin.system_health'),
            'breadcrumbs' => [['label' => lang('admin.administration'), 'url' => '/admin/system-health'], ['label' => lang('admin.system_health')]],
            'health' => $health,
            'recentErrors' => $recentErrors,
        ]);
    }
}