<?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; }
      </style>
   </head>

   <body>
      <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 Créditos
                </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>