<?php
$user = current_user();
$page = $_GET['page'] ?? 'home';
$isAuthenticated = (bool)$user;
$isAdmin = $isAuthenticated && $user['role'] === 'admin';
$plan = $isAuthenticated ? get_user_plan($user['id']) : null;

// Ícones SVG para cada item de menu
$menuIcons = [
    'dashboard'      => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>',
    'user_ip_form'   => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>',
    'user_ips'       => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"/></svg>',
    'user_logs'      => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>',
    'status_page'    => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"/></svg>',
    'nms_dashboard'  => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/></svg>',
    'nms_devices'    => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 3H5a2 2 0 00-2 2v4m6-6h10a2 2 0 012 2v4M9 3v18m0 0h10a2 2 0 002-2v-4M9 21H5a2 2 0 01-2-2v-4m0 0h18"/></svg>',
    'nms_alerts'     => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"/></svg>',
    'admin_dashboard'=> '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>',
    'admin_users'    => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"/></svg>',
    'admin_plans'    => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"/></svg>',
    'admin_ips'      => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9"/></svg>',
    'admin_logs'     => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>',
    'admin_settings' => '<svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>',
];

$mainMenu = [
    [
        'label' => 'Dashboard',
        'page'  => 'dashboard',
        'href'  => BASE_URL . 'index.php?page=dashboard',
        'match' => ['home', 'dashboard'],
    ],
    [
        'label' => 'Adicionar IP',
        'page'  => 'user_ip_form',
        'href'  => BASE_URL . 'index.php?page=user_ip_form',
        'match' => ['user_ip_form'],
    ],
    [
        'label' => 'Meus IPs',
        'page'  => 'user_ips',
        'href'  => BASE_URL . 'index.php?page=user_ips',
        'match' => ['user_ips'],
    ],
    [
        'label' => 'Logs',
        'page'  => 'user_logs',
        'href'  => BASE_URL . 'index.php?page=user_logs',
        'match' => ['user_logs'],
    ],
    [
        'label' => 'Status Page',
        'page'  => 'status_page',
        'href'  => BASE_URL . 'index.php?page=status_page',
        'match' => ['status_page'],
    ],
];

$nmsMenu = [
    [
        'label' => 'NMS MikroTik',
        'page'  => 'nms_dashboard',
        'href'  => BASE_URL . 'mikrotik/index.php?page=nms_dashboard',
        'match' => ['nms_dashboard'],
    ],
    [
        'label' => 'NMS Dispositivos',
        'page'  => 'nms_devices',
        'href'  => BASE_URL . 'mikrotik/index.php?page=nms_devices',
        'match' => ['nms_devices', 'nms_device_form', 'nms_device_detail'],
    ],
    [
        'label' => 'Alertas NMS',
        'page'  => 'nms_alerts',
        'href'  => BASE_URL . 'mikrotik/index.php?page=nms_alerts',
        'match' => ['nms_alerts'],
    ],
];

$adminMenu = [
    [
        'label' => 'Dashboard Admin',
        'page'  => 'admin_dashboard',
        'href'  => BASE_URL . 'index.php?page=admin_dashboard',
        'match' => ['admin_dashboard'],
    ],
    [
        'label' => 'Usuários',
        'page'  => 'admin_users',
        'href'  => BASE_URL . 'index.php?page=admin_users',
        'match' => ['admin_users'],
    ],
    [
        'label' => 'Planos',
        'page'  => 'admin_plans',
        'href'  => BASE_URL . 'index.php?page=admin_plans',
        'match' => ['admin_plans'],
    ],
    [
        'label' => 'IPs Globais',
        'page'  => 'admin_ips',
        'href'  => BASE_URL . 'index.php?page=admin_ips',
        'match' => ['admin_ips'],
    ],
    [
        'label' => 'Logs Globais',
        'page'  => 'admin_logs',
        'href'  => BASE_URL . 'index.php?page=admin_logs',
        'match' => ['admin_logs'],
    ],
    [
        'label' => 'Configurações',
        'page'  => 'admin_settings',
        'href'  => BASE_URL . 'index.php?page=admin_settings',
        'match' => ['admin_settings'],
    ],
];

// Badge: contar IPs offline do usuário logado
$offlineBadge = 0;
$nmsOfflineBadge = 0;
if ($isAuthenticated) {
    try {
        $pdo = db();
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM monitored_ips WHERE user_id = ? AND last_status = 'offline' AND active = 1");
        $stmt->execute([$user['id']]);
        $offlineBadge = (int)$stmt->fetchColumn();

        $stmtNms = $pdo->prepare("SELECT COUNT(*) FROM nms_devices WHERE user_id = ? AND last_status = 'offline' AND active = 1");
        $stmtNms->execute([$user['id']]);
        $nmsOfflineBadge = (int)$stmtNms->fetchColumn();
    } catch (Throwable $e) { $offlineBadge = 0; $nmsOfflineBadge = 0; }
}

// Iniciais do usuário para o avatar
$userInitials = '';
foreach (explode(' ', trim($user['name'] ?? '')) as $part) {
    $userInitials .= mb_strtoupper(mb_substr($part, 0, 1));
    if (mb_strlen($userInitials) >= 2) break;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MonitorPing</title>
    <link rel="stylesheet" href="<?php echo BASE_URL; ?>public/css/styles.css">
</head>
<body>
<div class="layout <?php echo $isAuthenticated ? 'layout-authenticated' : 'layout-public'; ?>">
    <?php if ($isAuthenticated): ?>
        <aside class="sidebar">

            <!-- Logo -->
            <div class="sidebar-logo">
                <div class="sidebar-logo-icon">
                    <svg width="20" height="20" fill="none" stroke="#fff" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"/></svg>
                </div>
                <span>MonitorPing</span>
            </div>

            <!-- Menu principal -->
            <nav class="sidebar-nav">
                <?php foreach ($mainMenu as $item):
                    $active = in_array($page, $item['match'], true) ? 'active' : '';
                    $icon   = $menuIcons[$item['page']] ?? '';
                    $isMeusIps = $item['page'] === 'user_ips';
                ?>
                    <a class="sidebar-link <?php echo $active; ?>" href="<?php echo h($item['href']); ?>">
                        <?php if ($icon): ?><span class="sidebar-link-icon"><?php echo $icon; ?></span><?php endif; ?>
                        <span class="sidebar-link-label"><?php echo h($item['label']); ?></span>
                        <?php if ($isMeusIps && $offlineBadge > 0): ?>
                            <span class="sidebar-badge"><?php echo $offlineBadge; ?></span>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </nav>

            <!-- Separador NMS -->
            <div class="sidebar-divider">
                <span>Rede</span>
            </div>
            <nav class="sidebar-nav">
                <?php foreach ($nmsMenu as $item):
                    $active = in_array($page, $item['match'], true) ? 'active' : '';
                    $icon   = $menuIcons[$item['page']] ?? '';
                ?>
                    <a class="sidebar-link <?php echo $active; ?>" href="<?php echo h($item['href']); ?>">
                        <?php if ($icon): ?><span class="sidebar-link-icon"><?php echo $icon; ?></span><?php endif; ?>
                        <span class="sidebar-link-label"><?php echo h($item['label']); ?></span>
                        <?php if ($item['page'] === 'nms_alerts' && $nmsOfflineBadge > 0): ?>
                            <span class="sidebar-badge"><?php echo $nmsOfflineBadge; ?></span>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?>
            </nav>

            <!-- Separador Admin -->
            <?php if ($isAdmin): ?>
                <div class="sidebar-divider sidebar-divider-admin">
                    <span>Administração</span>
                </div>
                <nav class="sidebar-nav">
                    <?php foreach ($adminMenu as $item):
                        $active = in_array($page, $item['match'], true) ? 'active' : '';
                        $icon   = $menuIcons[$item['page']] ?? '';
                    ?>
                        <a class="sidebar-link sidebar-link-admin <?php echo $active; ?>" href="<?php echo h($item['href']); ?>">
                            <?php if ($icon): ?><span class="sidebar-link-icon"><?php echo $icon; ?></span><?php endif; ?>
                            <span class="sidebar-link-label"><?php echo h($item['label']); ?></span>
                        </a>
                    <?php endforeach; ?>
                </nav>
            <?php endif; ?>

            <!-- Footer com avatar -->
            <div class="sidebar-footer">
                <div class="sidebar-user">
                    <div class="sidebar-avatar"><?php echo h($userInitials); ?></div>
                    <div class="sidebar-user-info">
                        <span class="sidebar-user-name"><?php echo h($user['name']); ?></span>
                        <span class="sidebar-user-role"><?php echo $isAdmin ? 'Administrador' : 'Usuário'; ?></span>
                    </div>
                </div>
                <a class="sidebar-link logout-link" href="<?php echo BASE_URL; ?>index.php?page=logout">
                    <span class="sidebar-link-icon">
                        <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>
                    </span>
                    <span class="sidebar-link-label">Sair</span>
                </a>
            </div>

        </aside>
    <?php endif; ?>

    <div class="main">
        <header class="topbar <?php echo $isAuthenticated ? '' : 'topbar-public'; ?>">
            <?php if ($isAuthenticated): ?>
                <div class="topbar-info">
                    <p>Olá, <?php echo h($user['name']); ?> <span class="role-tag"><?php echo h($user['role']); ?></span></p>
                    <?php if ($plan): ?>
                        <small>Plano: <strong><?php echo h($plan['name']); ?></strong> • Até <?php echo (int)$plan['max_ips']; ?> IPs • Intervalo mínimo <?php echo (int)$plan['min_interval_seconds']; ?>s</small>
                    <?php endif; ?>
                </div>
                <div class="topbar-actions">
                    <?php if ($isAdmin): ?>
                        <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=admin_dashboard">Dashboard Admin</a>
                    <?php endif; ?>
                    <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=dashboard">Dashboard Usuário</a>
                    <span class="chip chip-plan"><?php echo $plan ? h($plan['name']) : 'Sem plano'; ?></span>
                    <span class="chip chip-live">Live</span>
                </div>
            <?php else: ?>
                <div class="topbar-info">
                    <span class="logo">MonitorPing</span>
                </div>
                <div class="topbar-actions">
                    <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=login">Login</a>
                    <a class="ghost-button" href="<?php echo BASE_URL; ?>index.php?page=register">Registrar</a>
                </div>
            <?php endif; ?>
        </header>
        <main class="container <?php echo $isAuthenticated ? '' : 'container-public'; ?>">
