<?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 (in_array($role, ['ultra-reseller','super-reseller'])) {
        $rolesSql = $role === 'ultra-reseller' ? "'super-reseller','reseller'" : "'reseller'";
        $result = $db->select('menualuser', 'COUNT(*) as count', "parent = :parent AND role IN ($rolesSql)", '', [':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 (in_array($role, ['ultra-reseller','super-reseller'])) {
        $rolesSql = $role === 'ultra-reseller' ? "'super-reseller','reseller'" : "'reseller'";
        $result = $db->select('menualuser', 'SUM(CASE WHEN credits = -1 THEN 0 ELSE credits END) as total', "parent = :parent AND role IN ($rolesSql)", '', [':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]);
    $credits = $result[0]['credits'] ?? 0;
    return is_unlimited_credits($credits) ? '∞' : $credits;
}

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 (in_array($role, ['ultra-reseller','super-reseller'])) {
        $rolesSql = $role === 'ultra-reseller' ? "'super-reseller','reseller'" : "'reseller'";
        $result = $db->select('menualuser', 'COUNT(*) as count', "parent = :parent AND role IN ($rolesSql) AND (credits > 0 OR credits = -1)", '', [':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: 16px; 
    border: 1px solid rgba(29, 185, 84, 0.2); 
    background: rgba(18, 18, 18, 0.85) !important;
    backdrop-filter: blur(10px);
    margin-bottom: 20px; 
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: hidden;
}

.dashboard-card:hover {
    transform: translateY(-5px);
    border-color: rgba(29, 185, 84, 0.5);
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
}

.dashboard-card .card-header { 
    background: linear-gradient(135deg, rgba(29, 185, 84, 0.15), rgba(255, 0, 0, 0.1));
    border-bottom: 1px solid rgba(29, 185, 84, 0.3);
    padding: 15px 20px; 
}

.dashboard-card .card-header h3, 
.dashboard-card .card-header h5 {
    background: linear-gradient(135deg, #1DB954, #FF0000);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    display: inline-block;
}

.stat-number { 
    font-size: 2.5rem; 
    font-weight: 700; 
    margin: 10px 0; 
    background: linear-gradient(135deg, #1DB954, #1ed760);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}

.stat-number-master { 
    font-size: 3rem; 
    font-weight: 800; 
}

.stat-label { 
    font-size: 0.9rem; 
    color: #b3b3b3; 
    text-transform: uppercase; 
    letter-spacing: 1px; 
}

.infinity-symbol { 
    font-size: 3.5rem; 
    font-weight: bold; 
    line-height: 1; 
    background: linear-gradient(135deg, #1DB954, #1ed760);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}

.info-box { 
    background: linear-gradient(135deg, rgba(29, 185, 84, 0.08), rgba(255, 0, 0, 0.05));
    border-left: 4px solid #1DB954; 
    padding: 15px; 
    margin-bottom: 10px; 
    border-radius: 12px; 
    transition: all 0.3s ease;
}

.info-box:hover {
    background: linear-gradient(135deg, rgba(29, 185, 84, 0.15), rgba(255, 0, 0, 0.08));
    transform: translateX(5px);
}

.info-box h6 { 
    color: #fff; 
    margin-bottom: 5px; 
}

.info-box h6 i {
    color: #1DB954;
    margin-right: 8px;
}

.info-box p { 
    color: #b3b3b3; 
    margin: 0; 
    font-size: 0.9rem; 
}

.action-btn { 
    background: rgba(29, 185, 84, 0.1); 
    border: 1px solid rgba(29, 185, 84, 0.3); 
    color: #fff; 
    padding: 12px; 
    border-radius: 40px; 
    text-align: center;
    display: block; 
    width: 100%; 
    margin-bottom: 10px; 
    transition: all 0.3s ease;
    font-weight: 500;
}

.action-btn:hover { 
    background: linear-gradient(135deg, #1DB954, #1aa34a);
    border-color: #1DB954;
    text-decoration: none; 
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(29, 185, 84, 0.3);
    color: #fff;
}

.action-btn i { 
    color: #1DB954; 
    margin-right: 10px;
    transition: all 0.3s ease;
}

.action-btn:hover i {
    color: #fff;
    transform: scale(1.1);
}

/* Badge estilo SpoTube */
.badge-spotube {
    background: linear-gradient(135deg, #1DB954, #1aa34a);
    color: #fff;
    padding: 5px 12px;
    border-radius: 40px;
    font-weight: 600;
}

.badge-danger-spotube {
    background: linear-gradient(135deg, #FF0000, #CC0000);
    color: #fff;
    padding: 5px 12px;
    border-radius: 40px;
    font-weight: 600;
}

/* Iconos en el dashboard */
.fa-2x {
    filter: drop-shadow(0 0 5px rgba(29, 185, 84, 0.3));
    transition: all 0.3s ease;
}

.dashboard-card:hover .fa-2x {
    transform: scale(1.1);
    filter: drop-shadow(0 0 10px rgba(29, 185, 84, 0.5));
}

/* Texto con degradado SpoTube */
.spotube-gradient-text {
    background: linear-gradient(135deg, #1DB954, #FF0000);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}
</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="fab fa-spotify" style="color: #1DB954;"></i>
                        <i class="fab fa-youtube" style="color: #FF0000;"></i>
                        Dashboard SpoTube
                    </h3>
                    <p class="mb-0 text-muted">
                        <i class="fas fa-user"></i> Usuario: <strong><?=htmlspecialchars($username)?></strong> | 
                        <i class="fas fa-tag"></i> Rol: <span class="badge-spotube"><?=role_label_ptbr($role)?></span>
                    </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="fas fa-music fa-2x mb-3" style="color: #1DB954;"></i>
                    <div class="stat-number <?= $role === 'master' ? 'stat-number-master' : '' ?>">
                        <?= ($role === 'master' || $myCredits === '∞') ? '<div class="infinity-symbol">∞</div>' : number_format((int)$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="fas fa-users fa-2x mb-3" style="color: #1DB954;"></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="fas fa-chart-line fa-2x mb-3" style="color: #1DB954;"></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="fas fa-check-circle fa-2x mb-3" style="color: #1DB954;"></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="fas fa-info-circle" style="color: #1DB954;"></i> 
                        Detalles de la Cuenta
                    </h5>
                </div>
                <div class="card-body">
                    <div class="info-box">
                        <h6><i class="fas fa-user-circle"></i> Información del Perfil</h6>
                        <p><i class="fas fa-user"></i> Nombre de Usuario: <strong><?=htmlspecialchars($username)?></strong></p>
                        <p><i class="fas fa-shield-alt"></i> Nivel de Acceso: <span class="badge-spotube"><?=role_label_ptbr($role)?></span></p>
                        <?php if($role === 'reseller'): ?>
                            <p><i class="fas fa-user-tie"></i> Administrado por: <strong><?=safe_html($parentName)?></strong></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="fas fa-bolt" style="color: #FF0000;"></i> 
                        Acciones Rápidas
                    </h5>
                </div>
                <div class="card-body">
                    <?php if ($role !== 'reseller'): ?>
                        <a href="myteam.php" class="action-btn">
                            <i class="fas fa-users"></i> Administrar Revendedores
                        </a>
                    <?php endif; ?>
                    <a href="user.php" class="action-btn">
                        <i class="fas fa-user-cog"></i> Editar Perfil
                    </a>
                </div>
            </div>
        </div>
    </div>

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