<?php
namespace App\Controllers;

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

use App\Core\Controller;
use App\Core\Database;
use App\Middleware\RoleGuard;

class AdminImpersonationController extends Controller
{
    public function index(): void
    {
        RoleGuard::allow(['superadmin']);

        $db = Database::getInstance();

        $users = $db->query("
            SELECT id, first_name, last_name, email
            FROM users
            ORDER BY id DESC
            LIMIT 50
        ")->fetchAll();

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

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

    public function loginAs(): void
    {
        RoleGuard::allow(['superadmin']);

        $userId = (int)($_GET['id'] ?? 0);

        if (!$userId) {
            die('Invalid user');
        }

        $_SESSION['impersonator'] = $_SESSION['user'];
        $_SESSION['user'] = [
            'id' => $userId,
            'role' => 'impersonated'
        ];

        header("Location: /easychair/");
        exit;
    }

    public function revert(): void
    {
        if (isset($_SESSION['impersonator'])) {
            $_SESSION['user'] = $_SESSION['impersonator'];
            unset($_SESSION['impersonator']);
        }

        header("Location: /easychair/admin/dashboard");
        exit;
    }
}
