<?php
ob_start();
ini_set('display_errors', 0);
include(__DIR__ . '/functions.php');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Check if user has an active session
if (!isset($_SESSION['name']) || !isset($_SESSION['loggedin'])) {
    header("Location: index.php");
    exit();
}

// Sair Logic
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// Session control variables
$user_logado = $_SESSION['name'];
$role_logada = $_SESSION['role']; // Ensure login saves 'role' in session

// --- REAL-TIME CREDIT FETCH ---
$user_credits = 0;
if ($role_logada !== 'master') {
    // Fetch credits from menualuser table based on logged-in user
    $userData = $db->select('menualuser', 'credits', 'username = :user', '', [':user' => $user_logado]);
    $user_credits = isset($userData[0]['credits']) ? (int)$userData[0]['credits'] : 0;
}

// 15-minute timeout (900 seconds)
$timeout_duration = 900;
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: index.php?error=timeout");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time();

// Global sanitization function
function sanitize($data) {
    $data = trim($data);
    $data = htmlspecialchars($data, ENT_QUOTES);
    return $data;
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
   <head>
      <title>Rgvip Panel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="author" content="RTX">
      <link rel="icon" type="image/x-icon" href="./img/favicon.ico">
      <link rel="apple-touch-icon" sizes="180x180" href="./img/apple-touch-icon.png">
      <link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png">
      <link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png">
      <link rel="manifest" href="./img/site.webmanifest">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
      <link href="css/themes/darkly/bootstrap.css" rel="stylesheet" title="main">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.2.3/animate.min.css">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
      <link href="css/simple-sidebar.css" rel="stylesheet">
      <link href="css/style.css" rel="stylesheet">
      <style>
         body{background-color: #181828;background-image: url("./img/binding_dark.webp"); color: #fff;}
         #pageMessages { left: 50%; transform: translateX(-50%); position:fixed; text-align: center; top: 5px; width: 60%; z-index:9999; border-radius:0px}
         .sidebar-credits { padding: 15px; background: rgba(0,0,0,0.2); border-bottom: 1px solid rgba(255,255,255,0.1); text-align: center; }
         .credit-count { font-size: 1.5rem; font-weight: bold; color: #28a745; }
         .credit-low { color: #dc3545 !important; }
         /* Estilos base */
body {
    background-color: #0a0a0a;
    background-image: none;
    color: #fff;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* Fondo Vanta mejorado */
#net-canvas {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
    opacity: 0.8;
}

/* Asegurar que el contenido est???? sobre el canvas */
#wrapper, #page-content-wrapper {
    position: relative;
    z-index: 1;
}

/* Efecto Glassmorphism para el sidebar */
#sidebar-wrapper {
    background: rgba(20, 20, 40, 0.85) !important;
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border-right: 1px solid rgba(102, 126, 234, 0.3);
    box-shadow: 5px 0 25px rgba(0, 0, 0, 0.3);
}

.sidebar-heading {
    border-bottom: 1px solid rgba(102, 126, 234, 0.3);
    padding: 1rem;
}

.sidebar-logo img {
    filter: drop-shadow(0 0 10px rgba(102, 126, 234, 0.5));
    transition: all 0.3s ease;
}

.sidebar-logo img:hover {
    transform: scale(1.05);
    filter: drop-shadow(0 0 15px rgba(102, 126, 234, 0.8));
}

/* Tarjetas con efecto vidrio */
.card, .ctluser-main, .ctcard {
    background: rgba(30, 30, 50, 0.7) !important;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(102, 126, 234, 0.2);
    border-radius: 16px !important;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    overflow: hidden;
}

.card:hover, .ctluser-main:hover, .ctcard:hover {
    transform: translateY(-5px);
    border-color: rgba(102, 126, 234, 0.5);
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
}

/* Botones con gradiente y efecto hover */
.btn-primary, .ctbtn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
    border: none !important;
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    border-radius: 8px !important;
    padding: 10px 20px;
    font-weight: 500;
}

.btn-primary:hover, .ctbtn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}

.btn-danger {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
    border: none !important;
}

.btn-danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 20px rgba(245, 87, 108, 0.4);
}

/* Efecto ripple en botones */
.btn-primary:active, .ctbtn:active {
    transform: translateY(0px);
}

/* Links del sidebar con hover moderno */
.list-group-item {
    background: transparent !important;
    border: none !important;
    color: #e0e0e0;
    transition: all 0.3s ease;
    margin: 5px 10px;
    border-radius: 10px !important;
}

.list-group-item:hover {
    background: rgba(102, 126, 234, 0.2) !important;
    transform: translateX(5px);
    color: #fff;
}

.list-group-item.active {
    background: linear-gradient(135deg, #667eea, #764ba2) !important;
    color: white;
    box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

/* Cr????ditos con animaci????n */
.sidebar-credits {
    background: rgba(0, 0, 0, 0.3);
    margin: 10px;
    border-radius: 12px;
    padding: 15px;
    text-align: center;
    border: 1px solid rgba(102, 126, 234, 0.3);
}

.credit-count {
    font-size: 1.8rem;
    font-weight: bold;
    background: linear-gradient(135deg, #667eea, #764ba2);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.7; }
}

.credit-low {
    background: linear-gradient(135deg, #f093fb, #f5576c);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
}

/* Tablas modernas */
.table {
    background: rgba(30, 30, 50, 0.5);
    border-radius: 12px;
    overflow: hidden;
}

.table thead th {
    background: rgba(102, 126, 234, 0.3);
    border-bottom: 2px solid #667eea;
    color: #fff;
    font-weight: 600;
}

.table tbody tr {
    transition: all 0.3s ease;
}

.table tbody tr:hover {
    background: rgba(102, 126, 234, 0.1);
    transform: scale(1.01);
}

/* Inputs modernos */
input, select, textarea {
    background: rgba(20, 20, 40, 0.8) !important;
    border: 1px solid rgba(102, 126, 234, 0.3) !important;
    color: #fff !important;
    border-radius: 8px !important;
    transition: all 0.3s ease;
}

input:focus, select:focus, textarea:focus {
    border-color: #667eea !important;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2) !important;
    transform: translateY(-2px);
}

/* Navbar mejorada */
.ctnav {
    background: rgba(20, 20, 40, 0.8) !important;
    backdrop-filter: blur(10px);
    border-bottom: 1px solid rgba(102, 126, 234, 0.3);
    border-radius: 0 0 16px 16px;
    margin-bottom: 20px;
}

/* Mensajes flotantes mejorados */
#pageMessages {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9999;
    width: auto;
    min-width: 300px;
    animation: slideDown 0.5s ease;
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateX(-50%) translateY(-50px);
    }
    to {
        opacity: 1;
        transform: translateX(-50%) translateY(0);
    }
}

/* Scrollbar personalizada */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.3);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb {
    background: linear-gradient(135deg, #667eea, #764ba2);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #764ba2;
}

/* Animaciones de entrada */
.card, .ctluser-main, .ctcard {
    animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

/* Responsive */
@media (max-width: 768px) {
    .card, .ctluser-main, .ctcard {
        margin: 10px;
    }
    
    .credit-count {
        font-size: 1.2rem;
    }
    
    .btn-primary, .ctbtn {
        padding: 6px 12px;
        font-size: 12px;
    }
}
      </style>
   </head>

   <body>
       <div id="loading-overlay" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #0a0a0a; z-index: 9999; display: flex; justify-content: center; align-items: center; transition: opacity 0.5s;">
    <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
        <span class="sr-only">Cargando...</span>
    </div>
</div>

<script>
// Ocultar overlay cuando la p????gina cargue
window.addEventListener('load', function() {
    const overlay = document.getElementById('loading-overlay');
    if(overlay) {
        overlay.style.opacity = '0';
        setTimeout(() => overlay.style.display = 'none', 500);
    }
});
</script>
      <div id="net-canvas"></div> 
      <div class="d-flex" id="wrapper">
         
         <div class="" id="sidebar-wrapper">
            <div class="sidebar-heading">
               <div class="sidebar-logo">
                <img src="./img/loginn_logo.png" alt="logo">
              </div>
            </div>
            
            <div class="sidebar-credits">
                <?php if (in_array($role_logada, ['master','super-reseller'])): ?>
                    <span class="badge badge-primary"><i class="fa fa-star"></i> Acceso Master</span>
                <?php else: ?>
                    <small class="text-muted">MIS CR??DITOS</small><br>
                    <span class="credit-count <?= ($user_credits < 5) ? 'credit-low' : '' ?>">
                        <i class="fa fa-database"></i> <?=$user_credits?>
                    </span>
                <?php endif; ?>
            </div>

            <span><a class="list-group-item" href="<?php echo $config_ini['contact']; ?>" target="_blank"><?php echo $config_ini['panel_name']; ?></a> </span>  

            <div class="list-group list-group-flush">

                <a class="list-group-item list-group-item-action" href="dashboard.php">
                    <i class="fa fa-dashboard"></i>&nbsp;&nbsp; Panel
                </a>

                <?php /* DNS SETTINGS HIDDEN
                <a class="list-group-item list-group-item-action" href="main.php">
                <i class="fa fa-cogs"></i>&nbsp;&nbsp; Configuraci¨®n DNS </a>
                */ ?>
                
                <a class="list-group-item list-group-item-action" href="clients.php">
                <i class="fa fa-code"></i>&nbsp;&nbsp; Usuarios </a>
       
                <a class="list-group-item list-group-item-action" href="addclient.php">
                <i class="fa fa-user-plus"></i>&nbsp;&nbsp; Crear Usuarios </a>

                <?php if (in_array($role_logada, ['master','super-reseller'])): ?>
                <a class="list-group-item list-group-item-action" href="adduser.php">
                <i class="fa fa-users"></i>&nbsp;&nbsp; Crear Revendedores </a>
                <?php endif; ?>

                <?php if (in_array($role_logada, ['master', 'super-reseller'])): ?>
                <a class="list-group-item list-group-item-action" href="myteam.php">
                 <i class="fa fa-users"></i>&nbsp;&nbsp; Administrar Revendedores </a>
                <?php endif; ?>
                
                 <!--<?php if ($role_logada === 'master'): ?>
                <a class="list-group-item list-group-item-action" href="config_teste.php">
                 <i class="fa fa-cog"></i>&nbsp;&nbsp; Configuraci¨®n de Pruebas </a>
                <?php endif; ?>-->
                
                 <?php if ($role_logada === 'master'): ?>
                <a class="list-group-item list-group-item-action" href="gerenciar_testes.php">
                 <i class="fa fa-clock-o"></i>&nbsp;&nbsp; Administrar Pruebas </a>
                <?php endif; ?>

                <?php if (in_array($role_logada, ['master','super-reseller'])): ?>
                <a class="list-group-item list-group-item-action" href="credit_history.php">
                <i class="fa fa-history"></i>&nbsp;&nbsp; Historial de Creditos
                </a>
                <?php endif; ?>
<?php if ($role_logada === 'master'): ?>
                <a class="list-group-item list-group-item-action" href="backup.php">
                    <i class="fa fa-database"></i>&nbsp;&nbsp; Gestion de Backups
                </a>
                <?php endif; ?>

                <?php if ($role_logada === 'master'): ?>
                <a class="list-group-item list-group-item-action" href="id.php">
                    <i class="fa fa-telegram"></i>&nbsp;&nbsp; Obtener Chat ID
                </a>
                <?php endif; ?>
                <a class="list-group-item list-group-item-action" href="user.php">
                <i class="fa fa-user" ></i>&nbsp;&nbsp; Actualizar Credenciales </a>

            </div>
         </div>
         
         <div id="page-content-wrapper">
            <nav class="navbar navbar-expand-lg navbar-dark ctnav">
                <button class="btn btn-primary" id="menu-toggle"><i class="fa fa-bars"></i></button>
                
                <div class="ml-auto d-flex align-items-center">
                    <?php if ($role_logada !== 'master'): ?>
                        <div class="mr-3 d-none d-md-block">
                            <span class="text-white mr-2">Saldo:</span>
                            <span class="badge <?= ($user_credits < 5) ? 'badge-danger' : 'badge-success' ?>" style="font-size: 1rem;">
                                <?=$user_credits?>
                            </span>
                        </div>
                    <?php endif; ?>
                    
                    <a href="<?=basename($_SERVER["SCRIPT_NAME"]).'?logout'?>" class="btn btn-danger">
                        <i class="fa fa-sign-out"></i> Salir
                    </a> 
                </div>
            </nav>
            <div class="container-fluid">
               <br>
               <script src="./js/custom.js"></script>
      <script src="./js/three.min.js"></script>
      <script src="./js/vanta.net.min.js"></script>
      <script>
document.addEventListener('DOMContentLoaded', function() {
    // Configuraci????n mejorada del efecto Vanta
    VANTA.NET({
        el: "#net-canvas",
        mouseControls: true,
        touchControls: true,
        gyroControls: false,
        minHeight: 200.00,
        minWidth: 200.00,
        scale: 1.00,
        scaleMobile: 1.00,
        color: 0x667eea,        // Color morado/azul moderno
        backgroundColor: 0x0a0a0a,
        points: 12.00,
        maxDistance: 22.00,
        spacing: 16.00,
        showDots: true
    });
});
</script>
<script>
// Efecto de scroll en navbar
window.addEventListener('scroll', function() {
    const navbar = document.querySelector('.ctnav');
    if (window.scrollY > 50) {
        navbar.style.background = 'rgba(20, 20, 40, 0.95)';
        navbar.style.backdropFilter = 'blur(15px)';
    } else {
        navbar.style.background = 'rgba(20, 20, 40, 0.8)';
        navbar.style.backdropFilter = 'blur(10px)';
    }
});

// Tooltips autom????ticos
document.querySelectorAll('[title]').forEach(el => {
    el.setAttribute('data-toggle', 'tooltip');
});
</script>