<?php
error_reporting(E_ERROR | E_PARSE);
ini_set('display_errors', '1');
require_once '../../includes/functions.php';
chkSession();

// --------------------------------------------
// ACCESS VALIDATION
// --------------------------------------------
if (!in_array($user_level_2, ['superadmin', 'developer', 'reseller']) && $user_id_2 != 1) {
    echo json_encode(['response' => 0, 'message' => 'Unauthorized']);
    exit;
}

$values = [];

// --------------------------------------------
// RESELLER COUNT
// --------------------------------------------
if (in_array($user_level_2, ['superadmin', 'developer']) || $user_id_2 == 1) {
    $qry = $db->sql_query("SELECT COUNT(*) AS total FROM users WHERE user_level='reseller'");
} else {
    $qry = $db->sql_query("SELECT COUNT(*) AS total FROM users WHERE user_level='reseller' AND upline='$user_id_2'");
}
$values['reseller'] = $db->sql_fetchrow($qry)['total'] ?? 0;

// --------------------------------------------
// USERS COUNT
// --------------------------------------------
$user_condition = "(user_level IN ('normal','bulk','trial'))";
if (!in_array($user_level_2, ['superadmin', 'developer']) && $user_id_2 != 1) {
    $user_condition .= " AND upline='$user_id_2'";
}
$qry_user = $db->sql_query("SELECT COUNT(*) AS total FROM users WHERE $user_condition");
$values['user'] = $db->sql_fetchrow($qry_user)['total'] ?? 0;

// User breakdown
foreach (['normal', 'bulk', 'trial'] as $type) {
    $condition = "user_level='$type'";
    if (!in_array($user_level_2, ['superadmin', 'developer']) && $user_id_2 != 1) {
        $condition .= " AND upline='$user_id_2'";
    }
    $qry = $db->sql_query("SELECT COUNT(*) AS total FROM users WHERE $condition");
    $values[$type] = $db->sql_fetchrow($qry)['total'] ?? 0;
}

// --------------------------------------------
// SERVERS + ONLINE COUNT
// --------------------------------------------
$q_server = $db->sql_query("SELECT COUNT(*) AS total FROM server_list");
$values['servercount'] = $db->sql_fetchrow($q_server)['total'] ?? 0;

if (in_array($user_level_2, ['superadmin', 'developer']) || $user_id_2 == 1) {
    $online = $db->sql_fetchrow($db->sql_query("
        SELECT 
            COALESCE(SUM(online),0) + 
            COALESCE(SUM(hysteria_online),0) + 
            COALESCE(SUM(ssh_online),0) AS total_online 
        FROM server_list WHERE status='1'
    "))['total_online'];
    $values['online'] = $online ?? 0;
} else {
    $qry_online = $db->sql_query("SELECT COUNT(*) AS total FROM users WHERE user_level IN ('normal','bulk','trial') AND active_address!='' AND upline='$user_id_2'");
    $values['online'] = $db->sql_fetchrow($qry_online)['total'] ?? 0;
}

// --------------------------------------------
// PROFILE INFO
// --------------------------------------------
$qry_info = $db->sql_query("SELECT * FROM users WHERE user_id='$user_id_2'");
$info = $db->sql_fetchrow($qry_info);
$values['profile_username'] = $info['user_name'] ?? '';
$values['profile_upline'] = $db->sql_fetchrow($db->sql_query("SELECT user_name FROM users WHERE user_id='{$info['upline']}'"))['user_name'] ?? '-';
$values['profile_credits'] = ($user_id_2 == 1) ? '99999' : ($info['credits'] ?? '0');

// --------------------------------------------
// RECENT ACTIVITY LOGS
// --------------------------------------------
$qry_activity = $db->sql_query("SELECT date, device_os, action FROM activity_logs WHERE user_id='$user_id_2' ORDER BY date DESC LIMIT 10");
$activity_html = '';
while ($row = $db->sql_fetchrow($qry_activity)) {
    $elapsed = $db->time_elapsed_string(strtotime($row['date']));
    $icon = 'fas fa-list-alt';
    if (stripos($row['action'], 'Login') !== false) $icon = 'fas fa-sign-in-alt';
    elseif (stripos($row['action'], 'Added new user') !== false) $icon = 'fas fa-user-plus';
    elseif (stripos($row['action'], 'blocked') !== false) $icon = 'fas fa-lock';
    elseif (stripos($row['action'], 'unblocked') !== false) $icon = 'fas fa-unlock';
    elseif (stripos($row['action'], 'deleted') !== false) $icon = 'fas fa-user-times';
    elseif (stripos($row['action'], 'device') !== false) $icon = 'fas fa-mobile';
    elseif (stripos($row['action'], 'Extended') !== false) $icon = 'fas fa-user-clock';
    elseif (stripos($row['action'], 'credits') !== false) $icon = 'fas fa-coins';
    elseif (stripos($row['action'], 'password') !== false) $icon = 'fas fa-user-lock';

    $activity_html .= "
        <li class='media'>
            <div class='activitys-icon bg-primary text-white shadow-primary'><i class='$icon'></i></div>
            <div class='media-body'>
                <div class='float-right text-primary text-small'>$elapsed</div>
                <div class='media-title text-small'>{$row['device_os']}</div>
                <span class='text-small text-muted'>{$row['action']}</span>
            </div>
        </li>";
}
$values['activity'] = $activity_html ?: '<li class="media text-center">No recent activity.</li>';

// --------------------------------------------
// SERVER LIST PREVIEW
// --------------------------------------------
$qry_server = $db->sql_query("SELECT server_name, flag FROM server_list ORDER BY server_id DESC LIMIT 5");
$servers_html = '';
while ($s = $db->sql_fetchrow($qry_server)) {
    $flag = strtolower($s['flag'] ?? 'us');
    $servers_html .= '<li class="list-group-item d-flex justify-content-between align-items-center">'
        .htmlspecialchars($s['server_name']).' <span class="flag-icon"><img src="https://flagcdn.com/'.$flag.'.svg" width="35" height="25"></span></li>';
}
$values['servers'] = $servers_html ?: '<li class="list-group-item text-center">No servers found.</li>';

// --------------------------------------------
// 🧑‍💼 TOP SALES RESELLERS
// --------------------------------------------
$topResellers = [];
$qry_top_resellers = $db->sql_query("
    SELECT u.user_name AS reseller_name, COUNT(c.user_id) AS clients
    FROM users u
    LEFT JOIN users c ON c.upline = u.user_id AND c.user_level IN ('normal','bulk','trial')
    WHERE u.user_level='reseller'
    GROUP BY u.user_id
    ORDER BY clients DESC
    LIMIT 3
");
while ($r = $db->sql_fetchrow($qry_top_resellers)) {
    $reseller = htmlspecialchars($r['reseller_name']);
    $clients = (int)$r['clients'];
    $topResellers[] = "
        <div class='dash-item'>
            <div class='dash-left'>
                <img src='profile/avatar-1.png' class='dash-icon' alt='user'>
                <span class='dash-name'>{$reseller}</span>
            </div>
            <span class='badge badge-primary badge-pillt'>{$clients} Clients</span>
        </div>
    ";
}
$values['topresellers'] = !empty($topResellers)
    ? implode('', $topResellers)
    : '<div class="text-center text-muted">No data available</div>';


// 👤 TOP BANDWIDTH USERS (Valid users only + reseller filter)
$topUsers = '';

$whereReseller = '';
if (!in_array($user_level_2, ['superadmin', 'developer']) && $user_id_2 != 1) {
    // Show only users under this reseller
    $whereReseller = "AND u.upline = '$user_id_2'";
}

// 👤 TOP BANDWIDTH USERS (Valid users only + reseller filter)
$topUsers = '';

$whereReseller = '';
if (!in_array($user_level_2, ['superadmin', 'developer']) && $user_id_2 != 1) {
    // Show only users under this reseller
    $whereReseller = "AND u.upline = '$user_id_2'";
}

$qry_top_users = $db->sql_query("
    SELECT 
        b.username AS username,
        SUM(b.bytes_received + b.bytes_sent) AS total_bytes
    FROM bandwidth_logs b
    LEFT JOIN users u ON b.username = u.user_name
    WHERE (b.bytes_received > 0 OR b.bytes_sent > 0)
    $whereReseller
    GROUP BY b.username
    HAVING total_bytes > 0
    ORDER BY total_bytes DESC
    LIMIT 3
");

if ($db->sql_numrows($qry_top_users) > 0) {
    while ($u = $db->sql_fetchrow($qry_top_users)) {
        $usageMB = $u['total_bytes'] / (1024 * 1024);
        $usageDisplay = ($usageMB >= 1024)
            ? number_format($usageMB / 1024, 2) . ' GB'
            : number_format($usageMB, 2) . ' MB';
        $username = htmlspecialchars($u['username']);

        $topUsers .= "
            <div class='dash-item'>
                <div class='dash-left'>
                    <img src='profile/avatar-1.png' class='dash-icon' alt='user'>
                    <span class='dash-name'>{$username}</span>
                </div>
                <span class='badge badge-primary badge-pillt'>{$usageDisplay}</span>
            </div>
        ";
    }
} else {
    $topUsers = '<div class="text-center text-muted">No data available</div>';
}

$values['topbandwidthusers'] = $topUsers;



/* ─────────────── TOP 5 BANDWIDTH SERVERS ─────────────── */
$topbandwidthservers = '';

// detect actual column name
$q_columns_srv = $db->sql_query("SHOW COLUMNS FROM server_list");
$bw_col_srv = '';
while ($col = $db->sql_fetchrow($q_columns_srv)) {
    if (preg_match('/bandwidth|traffic|data/i', $col['Field'])) {
        $bw_col_srv = $col['Field'];
        break;
    }
}

if ($bw_col_srv != '') {
    $q_topservers = $db->sql_query("
        SELECT server_name, flag, $bw_col_srv AS usage_value
        FROM server_list
        ORDER BY usage_value DESC
        LIMIT 3
    ");
    while ($row = $db->sql_fetchrow($q_topservers)) {
        $flag = strtolower($row['flag']);
        $usage = round($row['usage_value'], 2);
        $topbandwidthservers .= '<li class="list-group-item d-flex justify-content-between align-items-center">'
                              . '<span><img src="https://flagcdn.com/' . $flag . '.svg" width="25" height="18"> '
                              . htmlspecialchars($row['server_name']) . '</span>'
                              . '<span class="badge badge-primary badge-pill">' . $usage . ' GB</span></li>';
    }
} else {
    $topbandwidthservers = '<li class="list-group-item text-center text-muted">No bandwidth data found</li>';
}
if ($topbandwidthservers == '') {
    $topbandwidthservers = '<li class="list-group-item text-center text-muted">No servers found</li>';
}





// --------------------------------------------
// DOMAIN + LICENSE INFO
// --------------------------------------------
$domin = get_domain($_SERVER['SERVER_NAME']);
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://who-dat.as93.net/$domin",
    CURLOPT_RETURNTRANSFER => true
]);
$content = curl_exec($curl);
curl_close($curl);
$response = json_decode($content, true);

if (!empty($response['domain'])) {
    $created = strtotime($response['domain']['created_date']);
    $expired = strtotime($response['domain']['expiration_date']);
    $values['domain_name'] = $domin;
    $values['domain_created'] = date('F d, Y \a\t h:i:s A', $created);
    $values['domain_expired'] = date('F d, Y \a\t h:i:s A', $expired);
} else {
    $values['domain_name'] = $domin;
    $values['domain_created'] = 'Unavailable';
    $values['domain_expired'] = 'Unavailable';
}

// --------------------------------------------
// SUCCESS RESPONSE
// --------------------------------------------
$values['response'] = 1;
$values['topbandwidthservers'] = $topbandwidthservers;
echo json_encode($values);
?>
