<?php

declare(strict_types=1);

namespace ServerManager\Controllers;

use ServerManager\Core\App;
use ServerManager\Core\Session;
use ServerManager\Models\Server;
use ServerManager\Services\MonitoringService;
use ServerManager\Services\AuditService;

class DashboardController
{
    private \ServerManager\Core\View $view;
    private MonitoringService $monitoringService;
    private AuditService $auditService;

    public function __construct()
    {
        $this->view = App::getInstance()->getView();
        $this->monitoringService = new MonitoringService();
        $this->auditService = new AuditService();
    }

    public function index(): void
    {
        $serverModel = new Server();
        $userId = (int) Session::get('user_id');

        $accessibleIds = $serverModel->getAccessibleServerIds($userId);
        $stats = $this->monitoringService->getDashboardStats($accessibleIds);
        $servers = !empty($accessibleIds) ? array_values(array_filter($serverModel->findAll(true), function ($s) use ($accessibleIds) {
            return in_array((int) $s['id'], $accessibleIds, true);
        })) : [];

        $recentActivity = $this->auditService->getRecentActivity(10, $userId);

        $this->view->display('dashboard.index', [
            'title' => 'Dashboard - ServerManager',
            'stats' => $stats,
            'servers' => $servers,
            'recentActivity' => $recentActivity,
        ]);
    }

    public function stats(): void
    {
        $serverModel = new Server();
        $accessibleIds = $serverModel->getAccessibleServerIds((int) Session::get('user_id'));
        $stats = $this->monitoringService->getDashboardStats($accessibleIds);

        $this->view->json([
            'success' => true,
            'data' => $stats,
        ]);
    }

    public function refreshMetrics(): void
    {
        $this->monitoringService->collectAllMetrics();

        $this->view->json([
            'success' => true,
            'message' => 'Metrics refreshed',
        ]);
    }
}
