<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../db.php';

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

$username = $_SESSION['username'] ?? '';
$role     = $_SESSION['role'] ?? 'user';

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

$avatarUrl = !empty($avatar) ? "uploads/avatars/" . $avatar : "assets/img/default-avatar.png";

if ($role === 'super_admin') { $rLabel = 'SUPER ADMIN'; $rColor = '#ff7700'; $rBorder = 'rgba(255,119,0,.4)'; $rBg = 'rgba(255,119,0,.15)'; }
elseif ($role === 'admin')   { $rLabel = 'ADMIN';       $rColor = '#9b4dff'; $rBorder = 'rgba(155,77,255,.4)'; $rBg = 'rgba(155,77,255,.2)'; }
else                         { $rLabel = 'USER';         $rColor = '#00e5ff'; $rBorder = 'rgba(0,229,255,.3)';  $rBg = 'rgba(0,229,255,.1)'; }
?>

<header class="topbar">
    <div class="user-box" style="display:flex;align-items:center;gap:12px;">
        <div style="width:38px;height:38px;border-radius:50%;border:2px solid <?= $rColor ?>;background-color:#111;background-image:url('<?= htmlspecialchars($avatarUrl) ?>');background-size:cover;background-position:center;flex-shrink:0;"></div>
        <div>
            <div style="font-weight:600;line-height:1.2;"><?= htmlspecialchars($username) ?></div>
            <span style="font-size:10px;font-weight:700;padding:1px 7px;border-radius:20px;letter-spacing:.5px;background:<?= $rBg ?>;color:<?= $rColor ?>;border:1px solid <?= $rBorder ?>;"><?= $rLabel ?></span>
        </div>
    </div>
    <div class="brand-title" style="font-family:Orbitron,sans-serif;letter-spacing:2px;">BDMA APP</div>
    <div style="display:flex;align-items:center;gap:8px;">
        <?php if (isViewingAs()): ?>
        <a href="index.php?view_as=0&page=users" style="color:#ff7700;text-decoration:none;font-size:12px;padding:6px 12px;border:1px solid rgba(255,119,0,.4);border-radius:8px;">
            <i class="fa fa-xmark me-1"></i> Exit View
        </a>
        <?php endif; ?>
        <a href="logout.php" style="color:#666;text-decoration:none;font-size:12px;padding:6px 12px;border:1px solid rgba(255,255,255,.1);border-radius:8px;transition:all .2s;" onmouseover="this.style.color='#ff003c';this.style.borderColor='rgba(255,0,60,.4)'" onmouseout="this.style.color='#666';this.style.borderColor='rgba(255,255,255,.1)'">
            <i class="fa fa-right-from-bracket me-1"></i> Logout
        </a>
    </div>
</header>
