<?php
ob_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);

session_start();

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/permissions.php';

$activeCheck = $conn->prepare("SELECT is_active, role FROM users WHERE id=? LIMIT 1");
$activeCheck->bind_param("i", $_SESSION['user_id']);
$activeCheck->execute();
$activeCheck->bind_result($isActive, $dbRole);
$activeCheck->fetch();
$activeCheck->close();

if (!$isActive) {
    session_destroy();
    header('Location: login.php?err=deactivated');
    exit;
}

$_SESSION['role'] = $dbRole;

if (isSuperAdmin()) {
    if (isset($_GET['view_as']) && is_numeric($_GET['view_as'])) {
        $vaId = (int)$_GET['view_as'];
        if ($vaId === 0) {
            unset($_SESSION['view_as_id'], $_SESSION['view_as_role'], $_SESSION['view_as_name']);
        } else {
            $vaRes = $conn->query("SELECT id, username, role FROM users WHERE id=$vaId LIMIT 1")->fetch_assoc();
            if ($vaRes) {
                $_SESSION['view_as_id']   = $vaRes['id'];
                $_SESSION['view_as_role'] = $vaRes['role'];
                $_SESSION['view_as_name'] = $vaRes['username'];
            }
        }
        header('Location: index.php?page=' . ($_GET['page'] ?? 'dashboard'));
        exit;
    }
}

$userPerms = loadUserPermissions($conn);

$page = $_GET['page'] ?? 'dashboard';

$superAdminOnly = ['users', 'agent-log'];

$permGated = [
    'dashboard'  => 'can_view_dashboard',
    'reports'    => 'can_view_reports',
    'analytics'  => 'can_view_analytics',
    'earnings'   => 'can_view_earnings',
    'ip-analysis'=> 'can_view_ip',
    'commands'   => 'can_send_commands',
    'settings'   => 'can_view_settings',
    'cold-tokens'=> 'can_view_tokens',
    'archive'    => 'can_view_reports',
];

$allAllowed = array_merge(array_keys($permGated), $superAdminOnly);

if (in_array($page, $superAdminOnly, true) && !isSuperAdmin()) {
    $page = 'dashboard';
}

if (!isSuperAdmin() && !isViewingAs() && isset($permGated[$page]) && !hasPerm($permGated[$page])) {
    $page = '__denied__';
}

if (!in_array($page, array_merge($allAllowed, ['__denied__']), true)) {
    $page = 'dashboard';
}

$file = __DIR__ . '/pages/' . $page . '.php';

if ($page === '__denied__' || !is_file($file)) {
    $file = null;
}
?>

<?php include __DIR__ . '/includes/head.php'; ?>
<body>

<?php include __DIR__ . '/includes/sidebar.php'; ?>

<div class="main">
    <?php include __DIR__ . '/includes/topbar.php'; ?>
    <?php if (isViewingAs()): ?>
    <div style="background:linear-gradient(90deg,rgba(255,119,0,.2),rgba(255,119,0,.05));border-bottom:1px solid rgba(255,119,0,.4);padding:8px 20px;display:flex;align-items:center;justify-content:space-between;">
        <div style="font-size:13px;color:#ff7700;"><i class="fa fa-eye me-2"></i>Viewing as <strong><?= htmlspecialchars($_SESSION['view_as_name'] ?? '') ?></strong> <span style="font-size:11px;color:#aaa;">(<?= strtoupper($_SESSION['view_as_role'] ?? '') ?>)</span></div>
        <a href="index.php?view_as=0&page=users" style="font-size:12px;padding:4px 12px;background:rgba(255,119,0,.2);color:#ff7700;border:1px solid rgba(255,119,0,.4);border-radius:20px;text-decoration:none;"><i class="fa fa-xmark me-1"></i>Exit View</a>
    </div>
    <?php endif; ?>
    <?php if ($file): ?>
        <?php include $file; ?>
    <?php else: ?>
        <?php accessDenied(); ?>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>

</body>
</html>