<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Database;

require_once BASE_PATH . '/app/helpers/easychair_translate.php';

class AdminOnlineUsersController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function requireSuperAdmin(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        $role = (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');

        if ($role !== 'superadmin') {
            http_response_code(403);
            exit(function_exists('ec_t') ? ec_t('msg.access_denied','Access denied.') : 'Access denied.');
        }
    }

    public function index()
    {
        $this->requireSuperAdmin();

        $minutes = max(1, min(240, (int)($_GET['minutes'] ?? 15)));
        $q = trim((string)($_GET['q'] ?? ''));

        $where = "last_seen_at IS NOT NULL AND last_seen_at >= (NOW() - INTERVAL ? MINUTE)";
        $params = [$minutes];

        if ($q !== '') {
            $where .= " AND (email LIKE ? OR first_name LIKE ? OR last_name LIKE ? OR username LIKE ?)";
            $like = '%' . $q . '%';
            $params = array_merge($params, [$like,$like,$like,$like]);
        }

        $stmt = $this->db()->prepare("
            SELECT *
            FROM users
            WHERE $where
            ORDER BY last_seen_at DESC
            LIMIT 200
        ");
        $stmt->execute($params);
        $users = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $totalOnline = count($users);

        ob_start();
        require BASE_PATH . '/app/views/admin/online_users/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }
}
