<?php
include('includes/header.php');

/* =======================
   SECURITY
======================= */
if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$username = $_SESSION['name'];
$role     = $_SESSION['role'];

/* =======================
   CREDIT INFO
======================= */
// Fetch current balance for session update
$userData = $db->select(
    'menualuser',
    'credits',
    'username = :username',
    '',
    [':username' => $username]
);

if (!empty($userData)) {
    $_SESSION['credits'] = $userData[0]['credits'] ?? 0;
}

/* =======================
   STATISTICS FUNCTIONS
======================= */

function getUserCount($db, $role, $username) {
    if ($role === 'master') {
        $result = $db->select('menualuser', 'COUNT(*) as count', "role != 'master'", '', []);
        return $result[0]['count'] ?? 0;
    } elseif ($role === 'super-reseller') {
        $result = $db->select('menualuser', 'COUNT(*) as count', "parent = :parent AND role = 'reseller'", '', [':parent' => $username]);
        return $result[0]['count'] ?? 0;
    }
    return 0;
}

function getTotalCredits($db, $role, $username) {
    if ($role === 'master') {
        $result = $db->select('menualuser', 'SUM(credits) as total', "role != 'master'", '', []);
        return $result[0]['total'] ?? 0;
    } elseif ($role === 'super-reseller') {
        $result = $db->select('menualuser', 'SUM(credits) as total', "parent = :parent AND role = 'reseller'", '', [':parent' => $username]);
        return $result[0]['total'] ?? 0;
    }
    return 0;
}

function getMyCredits($db, $role, $username) {
    if ($role === 'master') return '∞';
    $result = $db->select('menualuser', 'credits', 'username = :username', '', [':username' => $username]);
    return $result[0]['credits'] ?? 0;
}

function getActiveUsers($db, $role, $username) {
    if ($role === 'master') {
        $result = $db->select('menualuser', 'COUNT(*) as count', "role != 'master' AND credits > 0", '', []);
        return $result[0]['count'] ?? 0;
    } elseif ($role === 'super-reseller') {
        $result = $db->select('menualuser', 'COUNT(*) as count', "parent = :parent AND role = 'reseller' AND credits > 0", '', [':parent' => $username]);
        return $result[0]['count'] ?? 0;
    }
    return 0;
}

function safe_html($value) {
    return ($value === null || $value === '') ? '-' : htmlspecialchars($value);
}

$userCount = getUserCount($db, $role, $username);
$totalCredits = getTotalCredits($db, $role, $username);
$myCredits = getMyCredits($db, $role, $username);
$activeUsers = getActiveUsers($db, $role, $username);

$parentName = 'N/A';
if ($role === 'reseller') {
    $parentInfo = $db->select('menualuser', 'username', 'username = (SELECT parent FROM menualuser WHERE username = :username)', '', [':username' => $username]);
    $parentName = $parentInfo[0]['username'] ?? 'N/A';
}
?>

<style>
.dashboard-card { border-radius: 5px; border: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2); margin-bottom: 20px; }
.dashboard-card .card-header { background: rgba(220, 53, 69, 0.2); border-bottom: 1px solid rgba(220, 53, 69, 0.3); padding: 15px 20px; }
.stat-number { font-size: 2.5rem; font-weight: 700; margin: 10px 0; color: #dc3545; }
.stat-number-master { font-size: 3rem; font-weight: 800; }
.stat-label { font-size: 0.9rem; color: #aaa; text-transform: uppercase; letter-spacing: 1px; }
.infinity-symbol { font-size: 3.5rem; font-weight: bold; line-height: 1; color: #dc3545; }
.info-box { background: rgba(255,255,255,0.05); border-left: 4px solid #dc3545; padding: 15px; margin-bottom: 10px; border-radius: 3px; }
.info-box h6 { color: #fff; margin-bottom: 5px; }
.info-box p { color: #aaa; margin: 0; font-size: 0.9rem; }
.action-btn { background: rgba(220, 53, 69, 0.1); border: 1px solid rgba(220, 53, 69, 0.3); color: #fff; padding: 12px; border-radius: 5px; text-align: left; display: block; width: 100%; margin-bottom: 10px; transition: all 0.3s; }
.action-btn:hover { background: rgba(220, 53, 69, 0.2); border-color: #dc3545; text-decoration: none; transform: translateY(-2px); }
.action-btn i { color: #dc3545; margin-right: 10px; }
</style>

<div class="col-md-12 mx-auto">
    
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h3 class="mb-0"><i class="fa fa-tachometer-alt"></i> Panel</h3>
                    <p class="mb-0 text-muted">Usuario: <?=htmlspecialchars($username)?> | Rol: <?=role_label_ptbr($role)?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-coins fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number <?= $role === 'master' ? 'stat-number-master' : '' ?>">
                        <?= ($role === 'master') ? '<div class="infinity-symbol">∞</div>' : number_format($myCredits, 0, ',', '.') ?>
                    </div>
                    <div class="stat-label">Créditos Disponibles</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-users fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?=$userCount?></div>
                    <div class="stat-label">Total de Usuarios</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-chart-line fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?=number_format($totalCredits, 0, ',', '.')?></div>
                    <div class="stat-label">Créditos de la Red</div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6">
            <div class="card dashboard-card">
                <div class="card-body text-center">
                    <i class="fa fa-check-circle fa-2x mb-3" style="color: #dc3545;"></i>
                    <div class="stat-number"><?=$activeUsers?></div>
                    <div class="stat-label">Usuarios Activos</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-info-circle"></i> Detalles de la Cuenta</h5>
                </div>
                <div class="card-body">
                    <div class="info-box">
                        <h6><i class="fa fa-user-circle"></i> Información del Perfil</h6>
                        <p>Nombre de Usuario: <strong><?=htmlspecialchars($username)?></strong></p>
                        <p>Nivel de Acceso: <span class="badge badge-danger"><?=role_label_ptbr($role)?></span></p>
                        <?php if($role === 'reseller'): ?>
                            <p>Administrado por: <?=safe_html($parentName)?></p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card dashboard-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fa fa-bolt"></i> Acciones</h5>
                </div>
                <div class="card-body">
                    <?php if ($role !== 'reseller'): ?>
                        <a href="myteam.php" class="action-btn"><i class="fa fa-users"></i> Administrar Revendedores</a>
                    <?php endif; ?>
                    <a href="user.php" class="action-btn"><i class="fa fa-user-cog"></i> Editar Perfil</a>
                </div>
            </div>
        </div>
    </div>

</div>

<?php include('includes/footer.php'); ?>