<?php
if(!defined('lightengine')) {
    die('What are you doing here?');
}

if (!$auth->getLoggedIn()) {
    header('location: index.php?act=login');
    return;
}

// Configurações iniciais
$id = $auth->getId();
$currentDate = date("Y-m-d H:i:s");
$emptyDate = "0000-00-00 00:00:00";
$device = 'one device';
$login = $auth->getLogin();

// Busca informações da conta
$accountQuery = $game_db->prepare('SELECT a_level, email FROM account_login WHERE id = ?');
$accountQuery->execute([$id]);
$accountData = $accountQuery->fetchObject();

$accountLevel = $accountData->a_level ?? 0;
$email = trim($accountData->email ?? '');

// CONSULTAS PARA USUÁRIOS ATIVOS
if($accountLevel == 99) { // ADMIN (99)
    $activeTokensQuery = $game_db->prepare('SELECT COUNT(*) AS valid FROM tokens WHERE EndDate > ? AND UID2 = ?');
    $activeTokensOtherQuery = $game_db->prepare('SELECT COUNT(*) AS valid FROM tokens WHERE EndDate > ? AND (UID2 IS NULL OR UID2 != ?)');
    
    $activeTokensQuery->execute([$currentDate, $device]);
    $activeTokensOtherQuery->execute([$currentDate, $device]);
} else { // VENDEDOR (30)
    $activeTokensQuery = $game_db->prepare('SELECT COUNT(*) AS valid FROM tokens WHERE EndDate > ? AND UID2 = ? AND Vendedor = ?');
    $activeTokensOtherQuery = $game_db->prepare('SELECT COUNT(*) AS valid FROM tokens WHERE EndDate > ? AND (UID2 IS NULL OR UID2 != ?) AND Vendedor = ?');
    
    $activeTokensQuery->execute([$currentDate, $device, $login]);
    $activeTokensOtherQuery->execute([$currentDate, $device, $login]);
}

// CONSULTAS PARA USUÁRIOS NÃO ATIVOS
if($accountLevel == 99) { // ADMIN (99)
    $expiredTokensQuery = $game_db->prepare('SELECT COUNT(*) AS expirad FROM tokens WHERE (EndDate = "0000-00-00 00:00:00" OR EndDate <= ?) AND UID2 = ?');
    $expiredTokensOtherQuery = $game_db->prepare('SELECT COUNT(*) AS expirad FROM tokens WHERE (EndDate = "0000-00-00 00:00:00" OR EndDate <= ?) AND (UID2 IS NULL OR UID2 != ?)');
    
    $expiredTokensQuery->execute([$currentDate, $device]);
    $expiredTokensOtherQuery->execute([$currentDate, $device]);
} else { // VENDEDOR (30)
    $expiredTokensQuery = $game_db->prepare('SELECT COUNT(*) AS expirad FROM tokens WHERE (EndDate = "0000-00-00 00:00:00" OR EndDate <= ?) AND UID2 = ? AND Vendedor = ?');
    $expiredTokensOtherQuery = $game_db->prepare('SELECT COUNT(*) AS expirad FROM tokens WHERE (EndDate = "0000-00-00 00:00:00" OR EndDate <= ?) AND (UID2 IS NULL OR UID2 != ?) AND Vendedor = ?');
    
    $expiredTokensQuery->execute([$currentDate, $device, $login]);
    $expiredTokensOtherQuery->execute([$currentDate, $device, $login]);
}

// Processa resultados
$activeTokens = (int)($activeTokensQuery->fetchColumn() ?? 0);
$expiredTokens = (int)($expiredTokensQuery->fetchColumn() ?? 0);
$activeOtherTokens = (int)($activeTokensOtherQuery->fetchColumn() ?? 0);
$expiredOtherTokens = (int)($expiredTokensOtherQuery->fetchColumn() ?? 0);

// Cálculo de totais
$totalActive = $activeTokens + $activeOtherTokens;
$totalExpired = $expiredTokens + $expiredOtherTokens;

// Informações de produtos
$products = [];
$productQuery = $game_db->query('SELECT * FROM products');
while($product = $productQuery->fetchObject()) {
    $products[] = [
        'lastupdate' => trim($product->last_update ?? ''),
        'version' => trim($product->version ?? ''),
        'status' => trim($product->status ?? ''),
        'type' => trim($product->mode ?? ''),
        'download' => trim($product->download ?? ''),
    ];
}

// Ranking de vendedores
$rankings = [];
$rankQuery = $game_db->query('SELECT name FROM account_login');
while($user = $rankQuery->fetchObject()) {
    $sales = $auth->rankVendas($user->name ?? '');
    $rankings[] = [
        'usuario' => $user->name ?? '',
        'vendas' => $sales
    ];
}

// Ordena ranking
usort($rankings, function($a, $b) {
    return $b['vendas'] <=> $a['vendas'];
});

$finalRanking = [];
foreach(array_slice($rankings, 0, 5) as $index => $rank) {
    $finalRanking[] = [
        'rank' => $index + 1,
        'user' => $rank['usuario'],
        'vendas' => $rank['vendas']
    ];
}

// Últimas vendas
$lastSales = [];
$salesQuery = $game_db->query('SELECT Username, Vendedor, StartDate, mode FROM tokens ORDER BY id DESC LIMIT 5');
while($sale = $salesQuery->fetchObject()) {
    $lastSales[] = [
        'user' => $sale->Username ?? '',
        'vendedor' => $sale->Vendedor ?? '',
        'data' => $sale->StartDate ?? '',
        'modo' => $sale->mode ?? '',
    ];
}

// Prepara dados para o template
$accountInfo = [
    'login' => $login,
    'jmes' => $accountLevel,
    'email' => empty($email) ? 'Not specified' : $email,
    'validos' => $totalActive,
    'expirados' => $totalExpired,
    'total' => number_format($totalActive * ($config['price']['injetorMobile']['1UID'] ?? 0), 0, '', ',')
];

// Exibe o template
$smarty->assign([
    'pagename' => 'Dashboard',
    'breadcrumbs' => [['url' => '', 'caption' => 'Dashboard']],
    'active' => 'account',
    'account' => $accountInfo,
    'modinfo' => $products,
    'rank' => $finalRanking,
    'lastsell' => $lastSales
]);

$smarty->display('pages/account/account.tpl');
?>