<?php
// Load announcements for display
require_once('/docker/whp/web/libs/announcement_manager.php');
$AnnouncementMgr = new announcement_manager();
$announcements = $AnnouncementMgr->get_active_announcements();

// Load user resource information
require_once('/docker/whp/web/libs/mysqlmgmt.php');
require_once('/docker/whp/web/libs/emailmgmt.php');
$MySQLMgmt = new mysqlmgmt();
$EmailMgmt = new emailmgmt();

// Get server information
$server_info = [];
$server_info['hostname'] = trim(shell_exec('hostname'));
$server_info['ip_address'] = $_SERVER['SERVER_ADDR'] ?? 'Unknown';

// Load server settings from configuration
$server_settings = [];
if (file_exists('/docker/whp/settings.json')) {
    $settings_content = file_get_contents('/docker/whp/settings.json');
    if ($settings_content) {
        $server_settings = json_decode($settings_content, true) ?: [];
    }
}

$server_info['mail_server'] = $server_settings['mail_server'] ?? 'mail.example.com';

// Get nameservers from whp_nameservers configuration
if (isset($server_settings['whp_nameservers'])) {
    $server_info['nameservers'] = [
        $server_settings['whp_nameservers']['ns1'] ?? 'ns1.example.com',
        $server_settings['whp_nameservers']['ns2'] ?? 'ns2.example.com'
    ];
} else {
    $server_info['nameservers'] = $server_settings['nameservers'] ?? ['ns1.example.com', 'ns2.example.com'];
}

// Get live container memory stats from cgroups
function get_container_memory_stats($container_names) {
    $stats = [];
    foreach ($container_names as $name => $info) {
        $cid = trim(shell_exec("docker inspect " . escapeshellarg($name) . " --format '{{.Id}}' 2>/dev/null"));
        if (empty($cid)) continue;

        $cgroup_base = "/sys/fs/cgroup/system.slice/docker-{$cid}.scope";
        $current_file = "{$cgroup_base}/memory.current";
        $stat_file = "{$cgroup_base}/memory.stat";

        if (!file_exists($current_file) || !file_exists($stat_file)) continue;

        $total = intval(file_get_contents($current_file));
        $stat_content = file_get_contents($stat_file);

        $anon = 0;
        $file_cache = 0;
        if (preg_match('/^anon (\d+)/m', $stat_content, $m)) $anon = intval($m[1]);
        if (preg_match('/^file (\d+)/m', $stat_content, $m)) $file_cache = intval($m[1]);

        $stats[$name] = [
            'total_mb' => round($total / 1024 / 1024),
            'anon_mb' => round($anon / 1024 / 1024),
            'cache_mb' => round($file_cache / 1024 / 1024),
            'limit_mb' => $info['limit_mb'] ?? 0,
            'site_name' => $info['site_name'] ?? $name,
        ];
    }
    return $stats;
}

// Get current user's resource information
$current_user = defined('AUTH_USER') ? AUTH_USER : '';
$user_allowances = null;
$user_usage = null;
$system_overview = null;
$live_container_stats = [];
$account_type = $_SESSION['account_type'] ?? 'full';

if ($current_user) {
    if ($current_user === 'root') {
        // For root users, get system-wide overview
        $users_result = $MySQLMgmt->getAllSystemUsersWithResources();
        if ($users_result['status'] === '0') {
            $all_users = $users_result['users'];
            
            // Calculate system totals
            $total_allocated_cpu = 0;
            $total_allocated_memory = 0;
            $total_used_cpu = 0;
            $total_used_memory = 0;
            $total_users = count($all_users);
            $total_containers = 0;
            $total_domains = 0;
            $any_uncapped_users = false;

            foreach ($all_users as $user) {
                if (!empty($user['uncapped_resources'])) {
                    $any_uncapped_users = true;
                }

                $usage = $MySQLMgmt->getUserResourceUsage($user['username']);

                if (!empty($user['uncapped_resources'])) {
                    // Uncapped: cap value is meaningless; contribute actual current usage so
                    // the overview reflects real load on the box.
                    $total_allocated_cpu    += floatval($usage['cpu_used'] ?? 0);
                    $total_allocated_memory += intval($usage['memory_used'] ?? 0);
                } else {
                    $total_allocated_cpu    += $user['max_cpu_allowance'];
                    $total_allocated_memory += $user['max_memory_allowance'];
                }

                $total_used_cpu += $usage['cpu_used'];
                $total_used_memory += $usage['memory_used'];
                $total_containers += $usage['containers'];
                $total_domains += $usage['domains'];
            }
            
            $system_overview = [
                'total_users' => $total_users,
                'total_allocated_cpu' => $total_allocated_cpu,
                'total_allocated_memory' => $total_allocated_memory,
                'total_used_cpu' => $total_used_cpu,
                'total_used_memory' => $total_used_memory,
                'total_containers' => $total_containers,
                'total_domains' => $total_domains
            ];
        }

        // Root: get live stats for all site containers
        $db = $MySQLMgmt->getMySQLConnection();
        if ($db) {
            $stmt = $db->query("
                SELECT sc.container_id, sc.container_number, sc.status,
                       s.site_name, s.memory_per_container, s.username,
                       COALESCE(sd.fqdn, d.domain_name) as primary_domain
                FROM whp.site_containers sc
                JOIN whp.sites s ON sc.site_id = s.id
                JOIN whp.domains d ON s.primary_domain_id = d.id
                LEFT JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                WHERE sc.status = 'running'
                ORDER BY s.username, primary_domain, sc.container_number
            ");
            $containers_for_stats = [];
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $safe_domain = str_replace('*.', 'wildcard.', $row['primary_domain']);
                $cname = $safe_domain . '-' . str_pad($row['container_number'], 2, '0', STR_PAD_LEFT);
                $containers_for_stats[$cname] = [
                    'limit_mb' => intval($row['memory_per_container']),
                    'site_name' => $row['site_name'],
                    'username' => $row['username'],
                    'domain' => $row['primary_domain'],
                ];
            }
            $live_container_stats = get_container_memory_stats($containers_for_stats);
            // Merge back the username/domain info
            foreach ($live_container_stats as $cname => &$stat) {
                if (isset($containers_for_stats[$cname])) {
                    $stat['username'] = $containers_for_stats[$cname]['username'];
                    $stat['domain'] = $containers_for_stats[$cname]['domain'];
                }
            }
            unset($stat);

            // Get server physical stats for root
            $server_physical = [
                'mem_total' => intval(trim(shell_exec("awk '/^MemTotal:/ {print int(\$2/1024)}' /proc/meminfo"))),
                'mem_available' => intval(trim(shell_exec("awk '/^MemAvailable:/ {print int(\$2/1024)}' /proc/meminfo"))),
                'swap_total' => intval(trim(shell_exec("awk '/^SwapTotal:/ {print int(\$2/1024)}' /proc/meminfo"))),
                'swap_used' => intval(trim(shell_exec("awk '/^SwapFree:/ {print int(\$2/1024)}' /proc/meminfo"))),
            ];
            $server_physical['mem_used'] = $server_physical['mem_total'] - $server_physical['mem_available'];
            $server_physical['swap_used'] = $server_physical['swap_total'] - $server_physical['swap_used'];
        }
    } else {
        // For regular users, get their own resource information
        $allowances_result = $MySQLMgmt->getClientAllowances($current_user);
        if ($allowances_result['status'] === '0') {
            $user_allowances = $allowances_result['allowances'];
        }
        $user_usage = $MySQLMgmt->getUserResourceUsage($current_user);

        // Get live container stats for this user's sites
        $db = $MySQLMgmt->getMySQLConnection();
        if ($db) {
            $stmt = $db->prepare("
                SELECT sc.container_id, sc.container_number, sc.status,
                       s.site_name, s.memory_per_container,
                       COALESCE(sd.fqdn, d.domain_name) as primary_domain
                FROM whp.site_containers sc
                JOIN whp.sites s ON sc.site_id = s.id
                JOIN whp.domains d ON s.primary_domain_id = d.id
                LEFT JOIN whp.site_domains sd ON s.id = sd.site_id AND sd.is_primary = 1
                WHERE sc.status = 'running' AND s.username = ?
                ORDER BY primary_domain, sc.container_number
            ");
            $stmt->execute([$current_user]);
            $containers_for_stats = [];
            foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                $safe_domain = str_replace('*.', 'wildcard.', $row['primary_domain']);
                $cname = $safe_domain . '-' . str_pad($row['container_number'], 2, '0', STR_PAD_LEFT);
                $containers_for_stats[$cname] = [
                    'limit_mb' => intval($row['memory_per_container']),
                    'site_name' => $row['site_name'],
                    'domain' => $row['primary_domain'],
                ];
            }
            $live_container_stats = get_container_memory_stats($containers_for_stats);
            foreach ($live_container_stats as $cname => &$stat) {
                if (isset($containers_for_stats[$cname])) {
                    $stat['domain'] = $containers_for_stats[$cname]['domain'];
                }
            }
            unset($stat);
        }

        // Get email usage
        $email_usage_result = $EmailMgmt->getEmailUsageStats($current_user);
        $email_usage = [];
        if ($email_usage_result['status'] === '0') {
            $email_usage = $email_usage_result;
        }
    }
}
?>

<div class="row g-4 mb-5">
    <!-- Server Announcements - Left Side (Bigger Box) -->
    <div class="col-lg-8">
        <div class="card h-100">
            <div class="card-header bg-primary text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-bullhorn me-2"></i>Server Announcements
                </h5>
            </div>
            <div class="card-body d-flex flex-column">
                <?php if (empty($announcements)): ?>
                    <div class="text-center py-4 flex-grow-1 d-flex flex-column justify-content-center">
                        <i class="fa fa-info-circle fa-3x text-muted mb-3"></i>
                        <p class="text-muted mb-0">No announcements at this time.</p>
                        <?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
                            <small class="text-muted">
                                <a href="index.php?page=announcements-management" class="text-decoration-none">
                                    Create your first announcement
                                </a>
                            </small>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="announcements-container flex-grow-1" style="overflow-y: auto;">
                        <?php foreach ($announcements as $announcement): ?>
                            <div class="announcement-item mb-3 p-3 border rounded <?php echo $announcement['pinned'] ? 'border-warning' : ''; ?>">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h6 class="mb-0 fw-bold">
                                        <?php if ($announcement['pinned']): ?>
                                            <i class="fa fa-thumb-tack text-warning me-2" title="Pinned"></i>
                                        <?php endif; ?>
                                        <?php echo htmlspecialchars($announcement['title']); ?>
                                    </h6>
                                    <div class="d-flex gap-1">
                                        <?php if ($announcement['pinned']): ?>
                                            <span class="badge bg-warning text-dark">
                                                <i class="fa fa-thumb-tack me-1"></i>Pinned
                                            </span>
                                        <?php endif; ?>
                                        <?php if ($announcement['priority'] > 0): ?>
                                            <?php 
                                                $priority_labels = [1 => 'High', 2 => 'Urgent'];
                                                $priority_colors = [1 => 'warning', 2 => 'danger'];
                                            ?>
                                            <span class="badge bg-<?php echo $priority_colors[$announcement['priority']]; ?>">
                                                <?php echo $priority_labels[$announcement['priority']]; ?>
                                            </span>
                                        <?php endif; ?>
                                        <small class="text-muted">
                                            <?php echo whp_local_time($announcement['created_at'], 'M j, Y'); ?>
                                        </small>
                                    </div>
                                </div>
                                <div class="announcement-content">
                                    <?php
                                    // $announcement['content'] is the pre-rendered HTML produced by
                                    // announcement_manager::markdown_to_html(), which escapes the raw
                                    // markdown via htmlspecialchars before the regex pipeline and
                                    // neutralizes javascript:/vbscript:/data: URLs in [text](url) links.
                                    // Echo as-is. If the schema ever changes to store raw HTML in this
                                    // column, this echo MUST be revisited (it would then reflect XSS).
                                    echo $announcement['content'];
                                    ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <?php if (defined('AUTH_USER') && AUTH_USER === 'root'): ?>
                        <div class="text-end mt-3">
                            <a href="index.php?page=announcements-management" class="btn btn-sm btn-outline-primary">
                                <i class="fa fa-edit me-1"></i>Manage Announcements
                            </a>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Right Side - Stacked Boxes -->
    <div class="col-lg-4">
        <!-- Server Load Box -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-server me-2"></i>Server Load
                </h5>
            </div>
            <div class="card-body">
                <?php $system_load = sys_getloadavg(); ?>
                <div class="row g-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">1 Minute Average:</span>
                            <span class="fw-bold"><?php echo number_format($system_load[0], 2); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">5 Minute Average:</span>
                            <span class="fw-bold"><?php echo number_format($system_load[1], 2); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-muted">15 Minute Average:</span>
                            <span class="fw-bold"><?php echo number_format($system_load[2], 2); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Account Information Box -->
        <div class="card">
            <div class="card-header bg-info text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-user me-2"></i>Account Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">User:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars(AUTH_USER); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-muted">Home Directory:</span>
                            <span class="fw-bold text-break"><?php echo htmlspecialchars(HOME_DIR); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Server Information Box -->
        <div class="card mt-4">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-info-circle me-2"></i>Server Information
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">Hostname:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($server_info['hostname']); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">IP Address:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($server_info['ip_address']); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">Mail Server:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($server_info['mail_server']); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">NS1:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($server_info['nameservers'][0] ?? 'ns1.example.com'); ?></span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">NS2:</span>
                            <span class="fw-bold"><?php echo htmlspecialchars($server_info['nameservers'][1] ?? 'ns2.example.com'); ?></span>
                        </div>
                    </div>
                    <?php
                    // LUKS data-drive encryption status. Shown only on servers
                    // where LUKS is provisioned — non-LUKS servers don't display
                    // a row at all (avoids "LUKS: disabled" noise on every dashboard).
                    require_once('/docker/whp/web/libs/luks_state.php');
                    if (luks_is_enabled()):
                        $luks_state_inline = luks_state_summary();
                        $luks_badge_class = $luks_state_inline['unlocked'] ? 'bg-success' : 'bg-danger';
                        $luks_badge_text  = $luks_state_inline['unlocked'] ? 'Unlocked' : 'LOCKED';
                    ?>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">/docker encryption:</span>
                            <span>
                                <span class="badge <?= $luks_badge_class ?>" title="<?= htmlspecialchars($luks_state_inline['reason'] ?: 'On ' . $luks_state_inline['mounted_on']) ?>"><?= $luks_badge_text ?></span>
                                <span class="small text-muted ms-1"><?= htmlspecialchars($luks_state_inline['backing_device']) ?></span>
                            </span>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Database & Cache Connection Info Box -->
        <div class="card mt-4">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-database me-2"></i>Database & Cache Connections
                </h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">MySQL Database:</span>
                            <span class="fw-bold">mysql:3306</span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center border-bottom pb-2 mb-2">
                            <span class="text-muted">PostgreSQL Database:</span>
                            <span class="fw-bold">postgresql:5432</span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="d-flex justify-content-between align-items-center">
                            <span class="text-muted">Memcache (Sessions):</span>
                            <span class="fw-bold">memcache:11211</span>
                        </div>
                    </div>
                </div>
                <div class="mt-3 p-2 bg-dark rounded">
                    <small class="text-muted">
                        <i class="fa fa-info-circle me-1"></i>
                        Use these Docker container names for your applications running in containers. MySQL is for MySQL databases, PostgreSQL is for PostgreSQL databases, Memcache is for session management.
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Resource Information Section -->
<?php if ($current_user): ?>
<div class="row g-4 mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="fa fa-pie-chart me-2"></i>
                    <?php echo ($current_user === 'root') ? 'System Resource Overview' : 'Your Resource Assignments'; ?>
                </h5>
            </div>
            <div class="card-body">
                <?php if ($current_user === 'root' && $system_overview): ?>
                    <!-- System Overview for Root Users -->
                    <div class="row g-4">
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-users fa-2x text-primary mb-2"></i>
                                <h5 class="mb-1"><?php echo $system_overview['total_users']; ?></h5>
                                <small class="text-muted">Hosting Users</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-globe fa-2x text-info mb-2"></i>
                                <h5 class="mb-1"><?php echo $system_overview['total_domains']; ?></h5>
                                <small class="text-muted">Total Domains</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-cubes fa-2x text-warning mb-2"></i>
                                <h5 class="mb-1"><?php echo $system_overview['total_containers']; ?></h5>
                                <small class="text-muted">Active Containers</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-cog fa-2x text-secondary mb-2"></i>
                                <h5 class="mb-1">
                                    <a href="index.php?page=user-resources" class="text-decoration-none">
                                        Manage
                                    </a>
                                </h5>
                                <small class="text-muted">User Resources</small>
                            </div>
                        </div>
                    </div>
                    
                    <hr class="my-4">
                    
                    <div class="row g-4">
                        <div class="col-md-6">
                            <h6 class="mb-3">CPU Resources</h6>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Allocated:</span>
                                <span class="fw-bold"><?php echo number_format($system_overview['total_allocated_cpu'], 2); ?> cores</span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Used:</span>
                                <span class="fw-bold"><?php echo number_format($system_overview['total_used_cpu'], 2); ?> cores</span>
                            </div>
                            <?php 
                            $cpu_usage_percent = $system_overview['total_allocated_cpu'] > 0 ? 
                                ($system_overview['total_used_cpu'] / $system_overview['total_allocated_cpu']) * 100 : 0;
                            ?>
                            <div class="progress">
                                <div class="progress-bar <?php echo $cpu_usage_percent > 80 ? 'bg-danger' : ($cpu_usage_percent > 60 ? 'bg-warning' : 'bg-success'); ?>" 
                                     role="progressbar" style="width: <?php echo min($cpu_usage_percent, 100); ?>%" 
                                     aria-valuenow="<?php echo $cpu_usage_percent; ?>" aria-valuemin="0" aria-valuemax="100">
                                    <?php echo number_format($cpu_usage_percent, 1); ?>%
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6 class="mb-3">Memory Resources</h6>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Allocated:</span>
                                <span class="fw-bold"><?php echo number_format($system_overview['total_allocated_memory']); ?> MB</span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Used:</span>
                                <span class="fw-bold"><?php echo number_format($system_overview['total_used_memory']); ?> MB</span>
                            </div>
                            <?php 
                            $memory_usage_percent = $system_overview['total_allocated_memory'] > 0 ? 
                                ($system_overview['total_used_memory'] / $system_overview['total_allocated_memory']) * 100 : 0;
                            ?>
                            <div class="progress">
                                <div class="progress-bar <?php echo $memory_usage_percent > 80 ? 'bg-danger' : ($memory_usage_percent > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                     role="progressbar" style="width: <?php echo min($memory_usage_percent, 100); ?>%"
                                     aria-valuenow="<?php echo $memory_usage_percent; ?>" aria-valuemin="0" aria-valuemax="100">
                                    <?php echo number_format($memory_usage_percent, 1); ?>%
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($any_uncapped_users)): ?>
                    <div class="row mt-2">
                        <div class="col-12">
                            <small class="text-muted">
                                <i class="fa fa-info-circle"></i>
                                Note: uncapped users counted by actual usage (their stored CPU/memory caps are not enforced).
                            </small>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($server_physical)): ?>
                    <hr class="my-4">
                    <h6 class="mb-3"><i class="fa fa-server me-1"></i> Server Physical Resources</h6>
                    <div class="row g-4 mb-3">
                        <div class="col-md-6">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">RAM:</span>
                                <span class="fw-bold"><?php echo number_format($server_physical['mem_used']); ?> / <?php echo number_format($server_physical['mem_total']); ?> MB</span>
                            </div>
                            <?php $mem_pct = $server_physical['mem_total'] > 0 ? ($server_physical['mem_used'] / $server_physical['mem_total']) * 100 : 0; ?>
                            <div class="progress">
                                <div class="progress-bar <?php echo $mem_pct > 80 ? 'bg-danger' : ($mem_pct > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                     role="progressbar" style="width: <?php echo min($mem_pct, 100); ?>%">
                                    <?php echo number_format($mem_pct, 1); ?>%
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Swap:</span>
                                <span class="fw-bold"><?php echo number_format($server_physical['swap_used']); ?> / <?php echo number_format($server_physical['swap_total']); ?> MB</span>
                            </div>
                            <?php $swap_pct = $server_physical['swap_total'] > 0 ? ($server_physical['swap_used'] / $server_physical['swap_total']) * 100 : 0; ?>
                            <div class="progress">
                                <div class="progress-bar <?php echo $swap_pct > 50 ? 'bg-danger' : ($swap_pct > 25 ? 'bg-warning' : 'bg-success'); ?>"
                                     role="progressbar" style="width: <?php echo min($swap_pct, 100); ?>%">
                                    <?php echo number_format($swap_pct, 1); ?>%
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($live_container_stats)): ?>
                    <hr class="my-4">
                    <h6 class="mb-3"><i class="fa fa-bar-chart me-1"></i> Live Container Memory Usage</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Site</th>
                                    <th>Container</th>
                                    <th>User</th>
                                    <th class="text-end">Actual</th>
                                    <th class="text-end">Cache</th>
                                    <th class="text-end">Total</th>
                                    <th class="text-end">Limit</th>
                                    <th style="width:120px">Usage</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($live_container_stats as $cname => $stat):
                                    $use_pct = $stat['limit_mb'] > 0 ? ($stat['anon_mb'] / $stat['limit_mb']) * 100 : 0;
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($stat['domain'] ?? ''); ?></td>
                                    <td><small><?php echo htmlspecialchars($cname); ?></small></td>
                                    <td><?php echo htmlspecialchars($stat['username'] ?? ''); ?></td>
                                    <td class="text-end"><strong><?php echo $stat['anon_mb']; ?> MB</strong></td>
                                    <td class="text-end"><?php echo $stat['cache_mb']; ?> MB</td>
                                    <td class="text-end"><?php echo $stat['total_mb']; ?> MB</td>
                                    <td class="text-end"><?php echo $stat['limit_mb']; ?> MB</td>
                                    <td>
                                        <div class="progress" style="height: 16px;">
                                            <div class="progress-bar <?php echo $use_pct > 80 ? 'bg-danger' : ($use_pct > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                                 style="width: <?php echo min($use_pct, 100); ?>%">
                                                <small><?php echo number_format($use_pct, 0); ?>%</small>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <small class="text-muted mt-2 d-block">Actual = real process memory | Cache = filesystem cache (reclaimable by kernel) | Usage % = actual vs limit</small>
                    <?php endif; ?>

                <?php elseif ($user_allowances && $user_usage): ?>
                    <!-- Individual User Resource Information -->
                    <div class="row g-4">
                        <!-- Domain count card: shown for all account types -->
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-globe fa-2x text-info mb-2"></i>
                                <h5 class="mb-1"><?php echo $user_usage['domains']; ?></h5>
                                <small class="text-muted">Your Domains</small>
                            </div>
                        </div>
                        <?php if ($account_type === 'full'): ?>
                        <!-- Container card: full only -->
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-cubes fa-2x text-warning mb-2"></i>
                                <h5 class="mb-1"><?php echo $user_usage['containers']; ?></h5>
                                <small class="text-muted">Active Sites</small>
                            </div>
                        </div>
                        <!-- Disk card: full only -->
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-hdd-o fa-2x text-success mb-2"></i>
                                <?php if (isset($user_usage['disk_used_mb']) && isset($user_usage['disk_quota_mb']) && $user_usage['disk_quota_mb'] > 0): ?>
                                    <?php
                                    $disk_used = $user_usage['disk_used_mb'];
                                    $disk_quota = $user_usage['disk_quota_mb'];
                                    $disk_percentage = ($disk_used / $disk_quota) * 100;
                                    ?>
                                    <h5 class="mb-1"><?php echo number_format($disk_used, 1); ?> / <?php echo number_format($disk_quota); ?> MB</h5>
                                    <div class="progress mt-2 mb-2" style="height: 6px;">
                                        <div class="progress-bar <?php echo $disk_percentage > 80 ? 'bg-danger' : ($disk_percentage > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                             role="progressbar" style="width: <?php echo min($disk_percentage, 100); ?>%"
                                             aria-valuenow="<?php echo $disk_percentage; ?>" aria-valuemin="0" aria-valuemax="100">
                                        </div>
                                    </div>
                                    <small class="text-muted"><?php echo number_format($disk_percentage, 1); ?>% used</small>
                                <?php else: ?>
                                    <h5 class="mb-1"><?php echo number_format($user_allowances['max_disk_space']); ?> MB</h5>
                                    <small class="text-muted">Disk Space Quota</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        <?php if ($account_type === 'full' || $account_type === 'mail_dns'): ?>
                        <!-- Email card: full and mail_dns -->
                        <div class="col-md-3">
                            <div class="text-center p-3 border rounded">
                                <i class="fa fa-envelope fa-2x text-secondary mb-2"></i>
                                <?php if (!empty($email_usage)): ?>
                                    <h5 class="mb-1"><?php echo $email_usage['current_accounts']; ?> / <?php echo $email_usage['max_accounts']; ?></h5>
                                    <small class="text-muted">Email Accounts</small>
                                <?php else: ?>
                                    <h5 class="mb-1"><?php echo $user_allowances['max_email_accounts']; ?></h5>
                                    <small class="text-muted">Email Accounts (Max)</small>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($account_type === 'full'): ?>
                    <hr class="my-4">

                    <div class="row g-4">
                        <?php
                        // Uncapped (dedicated-server-mode) users have no enforced
                        // cap, but the legacy max_*_allowance values stored on the
                        // row may be small placeholders. Computing used/cap as a
                        // percentage produced 800%+ red bars; replace with a flat
                        // "Unlimited" indicator and show absolute usage instead.
                        // user-resources.php already does this for the admin
                        // table; this brings the user-facing dashboard in line.
                        $is_uncapped = !empty($user_allowances['uncapped_resources']);
                        ?>
                        <div class="col-md-4">
                            <h6 class="mb-3">CPU Resources</h6>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Allocated:</span>
                                <span class="fw-bold">
                                    <?php if ($is_uncapped): ?>
                                        <span title="Dedicated-server mode — caps not enforced">&infin; Unlimited</span>
                                    <?php else: ?>
                                        <?php echo number_format($user_allowances['max_cpu_allowance'], 2); ?> cores
                                    <?php endif; ?>
                                </span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Used:</span>
                                <span class="fw-bold"><?php echo number_format($user_usage['cpu_used'], 2); ?> cores</span>
                            </div>
                            <?php if ($is_uncapped): ?>
                                <div class="progress">
                                    <div class="progress-bar bg-info" role="progressbar" style="width: 100%"
                                         aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                        &infin; Dedicated
                                    </div>
                                </div>
                                <small class="text-muted">Caps not enforced for this user</small>
                            <?php else: ?>
                                <?php
                                $cpu_usage_percent = $user_allowances['max_cpu_allowance'] > 0 ?
                                    ($user_usage['cpu_used'] / $user_allowances['max_cpu_allowance']) * 100 : 0;
                                ?>
                                <div class="progress">
                                    <div class="progress-bar <?php echo $cpu_usage_percent > 80 ? 'bg-danger' : ($cpu_usage_percent > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                         role="progressbar" style="width: <?php echo min($cpu_usage_percent, 100); ?>%"
                                         aria-valuenow="<?php echo $cpu_usage_percent; ?>" aria-valuemin="0" aria-valuemax="100">
                                        <?php echo number_format($cpu_usage_percent, 1); ?>%
                                    </div>
                                </div>
                                <small class="text-muted">Available: <?php echo number_format($user_allowances['max_cpu_allowance'] - $user_usage['cpu_used'], 2); ?> cores</small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4">
                            <h6 class="mb-3">Memory Resources</h6>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Allocated:</span>
                                <span class="fw-bold">
                                    <?php if ($is_uncapped): ?>
                                        <span title="Dedicated-server mode — caps not enforced">&infin; Unlimited</span>
                                    <?php else: ?>
                                        <?php echo number_format($user_allowances['max_memory_allowance']); ?> MB
                                    <?php endif; ?>
                                </span>
                            </div>
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="text-muted">Used:</span>
                                <span class="fw-bold"><?php echo number_format($user_usage['memory_used']); ?> MB</span>
                            </div>
                            <?php if ($is_uncapped): ?>
                                <div class="progress">
                                    <div class="progress-bar bg-info" role="progressbar" style="width: 100%"
                                         aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                        &infin; Dedicated
                                    </div>
                                </div>
                                <small class="text-muted">Caps not enforced for this user</small>
                            <?php else: ?>
                                <?php
                                $memory_usage_percent = $user_allowances['max_memory_allowance'] > 0 ?
                                    ($user_usage['memory_used'] / $user_allowances['max_memory_allowance']) * 100 : 0;
                                ?>
                                <div class="progress">
                                    <div class="progress-bar <?php echo $memory_usage_percent > 80 ? 'bg-danger' : ($memory_usage_percent > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                         role="progressbar" style="width: <?php echo min($memory_usage_percent, 100); ?>%"
                                         aria-valuenow="<?php echo $memory_usage_percent; ?>" aria-valuemin="0" aria-valuemax="100">
                                        <?php echo number_format($memory_usage_percent, 1); ?>%
                                    </div>
                                </div>
                                <small class="text-muted">Available: <?php echo number_format($user_allowances['max_memory_allowance'] - $user_usage['memory_used']); ?> MB</small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-4">
                            <h6 class="mb-3">Disk Space</h6>
                            <?php if (isset($user_usage['disk_used_mb']) && isset($user_usage['disk_quota_mb']) && $user_usage['disk_quota_mb'] > 0): ?>
                                <?php
                                $disk_used = $user_usage['disk_used_mb'];
                                $disk_quota = $user_usage['disk_quota_mb'];
                                $disk_percentage = ($disk_used / $disk_quota) * 100;
                                ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="text-muted">Quota:</span>
                                    <span class="fw-bold"><?php echo number_format($disk_quota); ?> MB</span>
                                </div>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="text-muted">Used:</span>
                                    <span class="fw-bold"><?php echo number_format($disk_used, 1); ?> MB</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar <?php echo $disk_percentage > 80 ? 'bg-danger' : ($disk_percentage > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                         role="progressbar" style="width: <?php echo min($disk_percentage, 100); ?>%"
                                         aria-valuenow="<?php echo $disk_percentage; ?>" aria-valuemin="0" aria-valuemax="100">
                                        <?php echo number_format($disk_percentage, 1); ?>%
                                    </div>
                                </div>
                                <small class="text-muted">Available: <?php echo number_format($disk_quota - $disk_used, 1); ?> MB</small>
                            <?php else: ?>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="text-muted">Quota:</span>
                                    <span class="fw-bold"><?php echo number_format($user_allowances['max_disk_space']); ?> MB</span>
                                </div>
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="text-muted">Used:</span>
                                    <span class="fw-bold text-muted">Not available</span>
                                </div>
                                <div class="progress">
                                    <div class="progress-bar bg-secondary" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                                        0%
                                    </div>
                                </div>
                                <small class="text-muted">Quota monitoring not active</small>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if (!empty($live_container_stats)): ?>
                    <hr class="my-4">
                    <h6 class="mb-3"><i class="fa fa-bar-chart me-1"></i> Your Sites — Live Memory Usage</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Site</th>
                                    <th class="text-end">Actual</th>
                                    <th class="text-end">Cache</th>
                                    <th class="text-end">Limit</th>
                                    <th style="width:140px">Usage</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($live_container_stats as $cname => $stat):
                                    $use_pct = $stat['limit_mb'] > 0 ? ($stat['anon_mb'] / $stat['limit_mb']) * 100 : 0;
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($stat['domain'] ?? $cname); ?></td>
                                    <td class="text-end"><strong><?php echo $stat['anon_mb']; ?> MB</strong></td>
                                    <td class="text-end"><?php echo $stat['cache_mb']; ?> MB</td>
                                    <td class="text-end"><?php echo $stat['limit_mb']; ?> MB</td>
                                    <td>
                                        <div class="progress" style="height: 16px;">
                                            <div class="progress-bar <?php echo $use_pct > 80 ? 'bg-danger' : ($use_pct > 60 ? 'bg-warning' : 'bg-success'); ?>"
                                                 style="width: <?php echo min($use_pct, 100); ?>%">
                                                <small><?php echo number_format($use_pct, 0); ?>%</small>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <small class="text-muted mt-2 d-block">Actual = real process memory | Cache = filesystem cache (auto-managed) | Usage % = actual vs limit</small>
                    <?php endif; ?>
                    <?php endif; ?><!-- end account_type === full -->

                    <div class="text-end mt-3">
                        <a href="index.php?page=domains" class="btn btn-sm btn-outline-primary me-2">
                            <i class="fa fa-globe me-1"></i>Manage Domains
                        </a>
                        <a href="index.php?page=database-management" class="btn btn-sm btn-outline-info">
                            <i class="fa fa-database me-1"></i>Manage Databases
                        </a>
                    </div>
                    
                <?php else: ?>
                    <!-- Fallback when resource data is not available -->
                    <div class="alert alert-info">
                        <i class="fa fa-info-circle"></i>
                        <strong>Resource information is being loaded...</strong>
                        <br><small>If this message persists, there may be an issue connecting to the resource database.</small>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?> 