<?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']) ? $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="es-ES">
   <head>
      <title>SpoTube Panel - Premium Streaming Generator</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="author" content="SpoTube">
      <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">
      <link href="css/themes/darkly/bootstrap.css" rel="stylesheet" title="main">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
      <link href="css/simple-sidebar.css" rel="stylesheet">
      <link href="css/style.css" rel="stylesheet">
      <style>
         body{
            background-color: #0a0a0a;
            background-image: none;
            color: #fff;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         }
         
         /* Fondo estático sin animación */
         #net-canvas {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 0;
            opacity: 0.8;
         }
         
         #wrapper, #page-content-wrapper {
            position: relative;
            z-index: 1;
         }
         
         /* Sidebar estilo SpoTube */
         #sidebar-wrapper {
            background: rgba(0, 0, 0, 0.85) !important;
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border-right: 1px solid rgba(29, 185, 84, 0.3);
            box-shadow: 5px 0 25px rgba(0, 0, 0, 0.3);
         }
         
         .sidebar-heading {
            border-bottom: 1px solid rgba(29, 185, 84, 0.3);
            padding: 1rem;
            text-align: center;
         }
         
         .sidebar-logo img {
            max-width: 120px;
            filter: drop-shadow(0 0 10px rgba(29, 185, 84, 0.5));
            transition: all 0.3s ease;
         }
         
         .sidebar-logo img:hover {
            transform: scale(1.05);
            filter: drop-shadow(0 0 15px rgba(29, 185, 84, 0.8));
         }
         
         /* Tarjetas con efecto vidrio */
         .card, .ctluser-main, .ctcard {
            background: rgba(18, 18, 18, 0.85) !important;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(29, 185, 84, 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(29, 185, 84, 0.5);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.3);
         }
         
         /* Botones estilo Spotify */
         .btn-primary, .ctbtn {
            background: linear-gradient(135deg, #1DB954 0%, #1aa34a 100%) !important;
            border: none !important;
            position: relative;
            overflow: hidden;
            transition: all 0.3s ease;
            border-radius: 40px !important;
            padding: 10px 24px;
            font-weight: 600;
         }
         
         .btn-primary:hover, .ctbtn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(29, 185, 84, 0.4);
            background: linear-gradient(135deg, #1ed760 0%, #1DB954 100%) !important;
         }
         
         .btn-danger {
            background: linear-gradient(135deg, #FF0000 0%, #CC0000 100%) !important;
            border: none !important;
            border-radius: 40px !important;
         }
         
         .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(255, 0, 0, 0.4);
            background: linear-gradient(135deg, #FF3333 0%, #FF0000 100%) !important;
         }
         
         .btn-success {
            background: linear-gradient(135deg, #1DB954 0%, #1aa34a 100%) !important;
            border: none !important;
            border-radius: 40px !important;
         }
         
         /* 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(29, 185, 84, 0.15) !important;
            transform: translateX(8px);
            color: #fff;
         }
         
         .list-group-item.active {
            background: linear-gradient(135deg, #1DB954, #1aa34a) !important;
            color: white;
            box-shadow: 0 5px 15px rgba(29, 185, 84, 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(29, 185, 84, 0.3);
         }
         
         .credit-count {
            font-size: 1.8rem;
            font-weight: bold;
            background: linear-gradient(135deg, #1DB954, #1ed760);
            -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, #FF0000, #CC0000);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
         }
         
         /* Tablas modernas */
         .table {
            background: rgba(18, 18, 18, 0.6);
            border-radius: 12px;
            overflow: hidden;
         }
         
         .table thead th {
            background: rgba(29, 185, 84, 0.2);
            border-bottom: 2px solid #1DB954;
            color: #fff;
            font-weight: 600;
         }
         
         .table tbody tr {
            transition: all 0.3s ease;
         }
         
         .table tbody tr:hover {
            background: rgba(29, 185, 84, 0.08);
            transform: scale(1.01);
         }
         
         /* Inputs modernos */
         input, select, textarea {
            background: rgba(0, 0, 0, 0.6) !important;
            border: 1px solid rgba(29, 185, 84, 0.3) !important;
            color: #fff !important;
            border-radius: 8px !important;
            transition: all 0.3s ease;
         }
         
         input:focus, select:focus, textarea:focus {
            border-color: #1DB954 !important;
            box-shadow: 0 0 0 3px rgba(29, 185, 84, 0.2) !important;
            transform: translateY(-2px);
         }
         
         /* Navbar mejorada */
         .ctnav {
            background: rgba(0, 0, 0, 0.8) !important;
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(29, 185, 84, 0.3);
            border-radius: 0 0 16px 16px;
            margin-bottom: 20px;
         }
         
         /* Badges estilo SpoTube */
         .badge-success {
            background: linear-gradient(135deg, #1DB954, #1aa34a) !important;
         }
         
         .badge-danger {
            background: linear-gradient(135deg, #FF0000, #CC0000) !important;
         }
         
         .badge-primary {
            background: linear-gradient(135deg, #1DB954, #1aa34a) !important;
         }
         
         /* 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, #1DB954, #1aa34a);
            border-radius: 4px;
         }
         
         ::-webkit-scrollbar-thumb:hover {
            background: #1ed760;
         }
         
         /* 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);
            }
         }
         
         /* Mix de ��conos Spotify + YouTube */
         .spoTube-mix {
            background: linear-gradient(135deg, #1DB954, #FF0000);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
         }
         
         /* Responsive */
         @media (max-width: 768px) {
            .card, .ctluser-main, .ctcard {
               margin: 10px;
            }
            
            .credit-count {
               font-size: 1.2rem;
            }
            
            .btn-primary, .ctbtn {
               padding: 6px 16px;
               font-size: 12px;
            }
         }
      
         /* Animaciones desactivadas por configuración del panel */
         *, *::before, *::after {
            animation: none !important;
            transition: none !important;
         }
         .card:hover, .ctluser-main:hover, .ctcard:hover, .list-group-item:hover, .btn-primary:hover, .ctbtn:hover, .btn-danger:hover {
            transform: none !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="SpoTube">-->
                  <div class="mt-2">
                     <i class="fab fa-spotify" style="color: #1DB954; font-size: 50px;"></i>
                     <i class="fab fa-youtube" style="color: #FF0000; font-size: 50px;"></i>
                  </div>
               </div>
            </div>
            
            <div class="sidebar-credits">
               <?php if (in_array($role_logada, ['master','ultra-reseller','super-reseller'])): ?>
                  <span class="badge badge-primary"><i class="fas fa-crown"></i> <?= role_label_es($role_logada) ?></span>
               <?php else: ?>
                  <small class="text-muted">MIS CRÉDITOS</small><br>
                  <span class="credit-count <?= (!is_unlimited_credits($user_credits) && (int)$user_credits < 5) ? 'credit-low' : '' ?>">
                     <i class="fas fa-music"></i> <?=display_credits($user_credits)?>
                  </span>
               <?php endif; ?>
            </div>

            <span><a class="list-group-item" href="<?php echo $config_ini['contact']; ?>" target="_blank"><i class="fas fa-headset"></i> <?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="fas fa-tachometer-alt"></i>&nbsp;&nbsp; Panel SpoTube
               </a>
               
               <a class="list-group-item list-group-item-action" href="clients.php">
                  <i class="fas fa-users"></i>&nbsp;&nbsp; Usuarios
               </a>
       
               <a class="list-group-item list-group-item-action" href="addclient.php">
                  <i class="fas fa-user-plus"></i>&nbsp;&nbsp; Crear Usuarios
               </a>

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

               <?php if (in_array($role_logada, ['master','ultra-reseller','super-reseller'])): ?>
                  <a class="list-group-item list-group-item-action" href="myteam.php">
                     <i class="fas fa-user-friends"></i>&nbsp;&nbsp; Administrar Revendedores
                  </a>
               <?php endif; ?>
               
               <?php if ($role_logada === 'master'): ?>
                  <a class="list-group-item list-group-item-action" href="gerenciar_testes.php">
                     <i class="fas fa-clock"></i>&nbsp;&nbsp; Administrar Pruebas
                  </a>
               <?php endif; ?>

               <?php if (in_array($role_logada, ['master','ultra-reseller','super-reseller'])): ?>
                  <a class="list-group-item list-group-item-action" href="credit_history.php">
                     <i class="fas 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="fas 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="fab fa-telegram"></i>&nbsp;&nbsp; Obtener Chat ID
                  </a>
               <?php endif; ?>
               
               <?php if ($role_logada === 'master'): ?>
               <a class="list-group-item list-group-item-action" href="api_gen.php">
               <i class="fas fa-key"></i>&nbsp;&nbsp; API Key App
              </a>
              <?php endif; ?>
               
               <a class="list-group-item list-group-item-action" href="user.php">
                  <i class="fas fa-user-cog"></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-success" id="menu-toggle"><i class="fas fa-bars"></i></button>
               
               <div class="ml-auto d-flex align-items-center">
                  <div class="mr-3 d-none d-md-block">
                     <span class="text-white mr-2">
                        <i class="fab fa-spotify" style="color: #1DB954;"></i>
                        <i class="fab fa-youtube" style="color: #FF0000;"></i>
                        <strong class="spoTube-mix"> SpoTube</strong>
                     </span>
                  </div>
                  
                  <?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 <?= (!is_unlimited_credits($user_credits) && (int)$user_credits < 5) ? 'badge-danger' : 'badge-success' ?>" style="font-size: 1rem;">
                           <i class="fas fa-music"></i> <?=display_credits($user_credits)?>
                        </span>
                     </div>
                  <?php endif; ?>
                  
                  <a href="<?=basename($_SERVER["SCRIPT_NAME"]).'?logout'?>" class="btn btn-danger">
                     <i class="fas fa-sign-out-alt"></i> Salir
                  </a> 
               </div>
            </nav>
            
            <div class="container-fluid">
               <br>
               
               <script>
                  window.addEventListener('scroll', function() {
                     const navbar = document.querySelector('.ctnav');
                     if (window.scrollY > 50) {
                        navbar.style.background = 'rgba(0, 0, 0, 0.95)';
                        navbar.style.backdropFilter = 'blur(15px)';
                     } else {
                        navbar.style.background = 'rgba(0, 0, 0, 0.8)';
                        navbar.style.backdropFilter = 'blur(10px)';
                     }
                  });
                  
                  document.querySelectorAll('[title]').forEach(el => {
                     el.setAttribute('data-toggle', 'tooltip');
                  });
               </script>
       
   </body>
</html>