<?php
ini_set('display_errors', 0);

// Ensure session is started
if(session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

include(__DIR__ . '/functions.php');

// Force login check - redirect to login page if not logged in
// Skip this check only for index.php (login page)
$current_page = basename($_SERVER['PHP_SELF']);
if ($current_page !== 'index.php') {
    // Simplified login check
    if (empty($_SESSION['loggedin'])) {
        header('Location: index.php');
        exit;
    }
}

$log_check = $db->select('user', '*', 'id = :id', '', [':id' => 1]);
$loggedinuser = !empty($log_check) ? $log_check[0]['username'] : null;

if (isset($_REQUEST['logout'])) {
	@session_start();
	@session_destroy();
	setcookie("auth","");
	echo "<script>window.location.href='index.php'</script>";
}

//logout due to session time
$time = $_SERVER['REQUEST_TIME'];

$timeout_duration = 900;
if (isset($_SESSION['LAST_ACTIVITY']) && 
	($time - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
	session_unset();
	session_destroy();
	session_start();
}
$_SESSION['LAST_ACTIVITY'] = $time;

//sanitize strings
function sanitize($data) {
	$data = trim($data);
	$data = htmlspecialchars($data, ENT_QUOTES );
	$data = SQLite3::escapeString($data);
	return $data;
}
?>

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>BouzTV Panel</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="author" content="BouzTV">
	  <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/5.15.4/css/all.min.css">
      <link href="css/style.css" rel="stylesheet">
	  <script src='./js/jquery.particleground.js'></script>
  	  <script src='./js/demo.js'></script>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <style>
        /* Theme variables */
        :root {
          /* Dark theme (default) */
          --primary: #264653;            /* Dark blue/teal */
          --primary-dark: #1d3540;       /* Darker version of primary */
          --primary-light: #2a9d8f;      /* Teal */
          --accent: #e9c46a;             /* Yellow/Gold */
          --accent-secondary: #f4a261;   /* Light Orange */
          --accent-tertiary: #e76f51;    /* Deep Orange */
          
          --dark: #1a2c35;              /* Near black with blue tint */
          --dark-gray: #264653;          /* Based on primary */
          --medium-gray: #336270;        /* Lighter gray */
          --light: #f8f9fa;              /* Off white */
          
          --text-primary: #e0e0e0;       /* Main text color - light */
          --text-muted: #b0b0b0;         /* Secondary text - lighter */
          --text-dark: #333333;          /* Dark text for light theme */
          
          /* Background and UI elements */
          --bg-main: var(--dark);        /* Main background */
          --bg-card: var(--dark-gray);   /* Card backgrounds */
          --border-color: var(--primary-light);  /* Border color */
          
          /* Status colors */
          --success: #2a9d8f;            /* Success messages */
          --warning: #e9c46a;            /* Warning messages */
          --error: #e76f51;              /* Error messages */
        }
        
        /* Light theme */
        [data-theme="light"] {
          --dark: #f8f9fa;              /* Now light */
          --dark-gray: #eaeaea;          /* Light gray */
          --medium-gray: #cccccc;        /* Medium gray */
          --light: #264653;              /* Now dark */
          
          --text-primary: #264653;       /* Main text now dark */
          --text-muted: #336270;         /* Secondary text darker */
          
          /* Background and UI elements */
          --bg-main: #ffffff;            /* Main background */
          --bg-card: #f0f0f0;            /* Card backgrounds */
          --border-color: #2a9d8f;       /* Border color */
        }

        body {
          background-color: var(--bg-main);
          color: var(--text-primary);
          font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
          padding-top: 60px;
          position: relative;
          min-height: 100vh;
          transition: all 0.3s ease;
        }
        
        /* Override for flat background colors */
        html {
          background-color: var(--bg-main);
          transition: background-color 0.3s ease;
        }
        
        html[data-theme="dark"] {
          background-color: #1a2c35; /* Flat dark color */
        }
        
        html[data-theme="light"] {
          background-color: #f8f9fa; /* Flat light color */
        }
        
        /* Theme toggle button */
        .theme-toggle {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: transparent;
          border: 2px solid var(--border-color);
          color: var(--text-primary);
          cursor: pointer;
          font-size: 18px;
          transition: all 0.3s ease;
          margin-left: 15px;
          outline: none;
          padding: 0;
        }
        
        .theme-toggle:hover {
          background-color: var(--primary-light);
          color: var(--light);
        }
        
        /* Cards and UI elements */
        .card {
          background-color: var(--bg-card);
          border: 1px solid var(--border-color);
          border-radius: 8px;
          box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
          transition: all 0.3s ease;
        }
        
        .card-header {
          background-color: var(--primary) !important;
          border-bottom: 2px solid var(--primary-light);
          color: var(--light);
        }
        
        /* Tables */
        .table {
          color: var(--text-primary);
          background-color: var(--bg-card);
        }
        
        .table thead th {
          background-color: var(--primary);
          color: var(--light);
          border-color: var(--primary-light);
        }
        
        .table-striped tbody tr:nth-of-type(odd) {
          background-color: rgba(0, 0, 0, 0.05);
        }
        
        [data-theme="light"] .table-striped tbody tr:nth-of-type(odd) {
          background-color: rgba(0, 0, 0, 0.02);
        }

        /* Barra de navegación moderna */
        .modern-navbar {
          background-color: var(--dark);
          box-shadow: 0 2px 10px rgba(0,0,0,0.3);
          padding: 0;
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          z-index: 1030;
          height: 60px;
          display: flex;
          align-items: center;
        }

        /* Contenedor de la barra para mantener el padding correcto */
        .navbar-container {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 0 15px;
        }

        /* Logo y branding */
        .brand-section {
          display: flex;
          align-items: center;
        }

        .logo {
          height: 38px;
          margin-right: 15px;
        }

        .brand-name {
          color: var(--text-primary);
          font-weight: 600;
          font-size: 18px;
          white-space: nowrap;
          margin: 0;
        }

        /* Navegación principal */
        .nav-container {
          flex: 1;
          display: flex;
          justify-content: center;
        }
        
        .main-nav {
          display: flex;
          margin: 0;
          padding: 0;
          list-style: none;
        }

        .nav-item {
          margin: 0;
          position: relative;
        }

        .nav-link {
          display: flex;
          align-items: center;
          text-decoration: none !important;
          color: var(--text) !important;
          position: relative;
          padding: 19px 20px;
          transition: all 0.3s ease;
          font-weight: 500;
          font-size: 14px;
          letter-spacing: 0.5px;
        }
        
        [data-theme="light"] .nav-link {
          color: var(--text-dark) !important;
        }

        .nav-link:hover {
          color: var(--accent) !important;
          background-color: rgba(255,255,255,0.05);
        }

        .nav-link.active {
          color: var(--light) !important;
          background-color: var(--accent-tertiary) !important;
        }
        
        [data-theme="light"] .nav-link.active {
          color: var(--light) !important;
          background-color: var(--accent-tertiary) !important;
        }

        /* Indicador activo con línea inferior */
        .nav-link.active::after {
          content: '';
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 3px;
          background-color: var(--accent);
        }

        .nav-link i {
          margin-right: 8px;
          width: 16px;
          text-align: center;
        }

        /* Botón de menú para móviles */
        .menu-toggle {
          display: none;
          background: transparent;
          border: none;
          color: var(--text-primary);
          font-size: 24px;
          cursor: pointer;
          padding: 5px;
          transition: color 0.3s ease;
        }
        
        [data-theme="light"] .menu-toggle {
          color: var(--primary);
        }

        .menu-toggle:focus {
          outline: none;
        }

        /* Botones de acción (logout y theme toggle) */
        .action-btn {
          display: flex;
          align-items: center;
        }
        
        /* Botón de cierre de sesión */
        .logout-btn {
          display: flex;
          align-items: center;
          background-color: var(--accent-tertiary); /* Using accent-tertiary color instead of primary */
          color: var(--light);
          border: none;
          padding: 8px 16px;
          border-radius: 4px;
          font-weight: 500;
          letter-spacing: 0.5px;
          transition: all 0.3s ease;
          font-size: 14px;
          text-decoration: none !important; /* Prevent text decoration override */
          margin-left: 10px;
        }
        
        [data-theme="light"] .logout-btn {
          background-color: var(--accent-tertiary); /* Same color in both themes for consistency */
          color: var(--light);
        }

        .logout-btn:hover {
          background-color: var(--accent-secondary); /* Using accent-secondary for hover */
          text-decoration: none !important;
          color: var(--light) !important; /* Ensure text stays light */
        }

        .logout-btn i {
          margin-right: 8px;
        }

        /* Contenido principal */
        .main-content {
          padding: 20px;
          margin-top: 10px;
        }

        /* Mensajes de sistema */
        #pageMessages {
          position: fixed;
          top: 70px;
          left: 50%;
          transform: translateX(-50%);
          width: 80%;
          max-width: 600px;
          z-index: 1000;
        }

        .alert {
          border-radius: 4px;
          box-shadow: 0 4px 10px rgba(0,0,0,0.2);
          margin-bottom: 10px;
        }

        /* Animación del fondo */
        #net-canvas {
          position: fixed;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: -1;
        }

       /* Responsive */
       @media (max-width: 992px) {
          /* Hacer que la barra no tenga altura fija en móvil */
          .modern-navbar {
            height: auto;
            min-height: 60px;
          }
          
          .menu-toggle {
            display: block;
            position: absolute;
            left: 15px;
            top: 18px;
            font-size: 22px;
            color: white;
          }
          
          .navbar-container {
            flex-wrap: wrap;
          }
          
          .brand-section {
            width: 100%;
            justify-content: center;
            text-align: center;
            margin-top: 10px;
          }
          
          .nav-container {
            order: 3;
            width: 100%;
            display: none;
            margin-top: 10px;
          }
          
          .nav-container.active {
            display: block;
          }
          
          .main-nav {
            flex-direction: column;
            width: 100%;
          }
          
          .nav-item {
            width: 100%;
            border-top: 1px solid rgba(255,255,255,0.1);
          }
          
          .nav-link {
            padding: 15px;
            width: 100%;
          }
          
          .nav-link.active::after {
            display: none;
          }
          
          /* Action buttons positioning on mobile */
          .action-btn {
            position: absolute;
            right: 15px;
            top: 18px;
            display: flex;
            align-items: center;
          }
          
          .theme-toggle {
            margin-right: 10px;
            width: 36px;
            height: 36px;
            font-size: 16px;
          }
          
          .logout-btn {
            padding: 5px 12px;
            font-size: 13px;
          }
        }

        /* Estilos para el footer opcional */
        .footer {
          text-align: center;
          padding: 15px 0;
          font-size: 12px;
          color: var(--text-muted);
          position: absolute;
          bottom: 0;
          width: 100%;
          background-color: var(--dark);
        }
      </style>
   </head>
   <body>
      <div id="net-canvas"></div>
      
      <!-- Barra de navegación moderna -->
      <nav class="modern-navbar">
        <div class="navbar-container">
          <!-- Logo y nombre -->
          <div class="brand-section">
            <img src="./img/login_logo.png" alt="BouzTV Logo" class="logo">
            <h1 class="brand-name"><?php echo $config_ini['panel_name']; ?></h1>
          </div>
          
          <!-- Botón para menú móvil -->
          <button type="button" class="menu-toggle" id="menuToggle">
            <i class="fa fa-bars"></i>
          </button>
          
          <!-- Contenedor de navegación - Centrado -->
          <div class="nav-container" id="navContainer">
            <ul class="main-nav">
              <li class="nav-item">
                <a class="nav-link" href="main.php">
                  <i class="fa fa-cogs"></i> DNS Settings
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="getid.php">
                  <i class="fa fa-id-badge"></i> Get Category ID
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="ads.php">
                  <i class="fa fa-bullhorn"></i> Ads
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="<?php echo $config_ini['contact']; ?>" target="_blank">
                  <i class="fa fa-envelope"></i> Contact
                </a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="user.php">
                  <i class="fa fa-user"></i> Update credentials
                </a>
              </li>
            </ul>
          </div>
          
          <!-- Botones de acción a la derecha -->
          <div class="action-btn">
            <!-- Theme toggle button -->
            <button id="themeToggle" class="theme-toggle" aria-label="Toggle theme">
              <i class="far fa-sun" id="themeIcon"></i>
            </button>
            
            <!-- Botón de logout -->
            <a href="<?=basename($_SERVER["SCRIPT_NAME"]).'?logout'?>" class="logout-btn">
              <i class="fa fa-sign-out"></i> Logout
            </a>
          </div>
        </div>
      </nav>
      
      <!-- Mensajes del sistema -->
      <div id="pageMessages"></div>
      
      <!-- Contenido principal -->
      <div class="container main-content">
        <!-- El contenido específico de cada página se insertará aquí directamente -->
      </div>
      
      <!-- Scripts -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
      <script src="./js/custom.js"></script>
      <script src="./js/three.min.js"></script>
      <script>
        $(document).ready(function() {
          // Theme switching functionality
          function setTheme(themeName) {
            // Set theme attribute on html element
            document.documentElement.setAttribute('data-theme', themeName);
            
            // Update the icon
            if (themeName === 'light') {
              $('#themeIcon').removeClass('far fa-sun').addClass('far fa-moon');
            } else {
              $('#themeIcon').removeClass('far fa-moon').addClass('far fa-sun');
            }
            
            // Save theme preference to localStorage
            localStorage.setItem('theme', themeName);
          }
          
          // Toggle between dark and light themes
          function toggleTheme() {
            if (localStorage.getItem('theme') === 'light') {
              setTheme('dark');
            } else {
              setTheme('light');
            }
          }
          
          // Set initial theme from localStorage or default to dark
          (function() {
            if (localStorage.getItem('theme') === 'light') {
              setTheme('light');
            } else {
              setTheme('dark');
            }
          })();
          
          // Handle theme toggle button click
          $('#themeToggle').click(function() {
            toggleTheme();
          });
          
          // Activar el menú móvil
          $("#menuToggle").click(function() {
            $("#navContainer").toggle();
          });
          
          // Marcar el enlace activo
          var currentPage = window.location.pathname.split("/").pop();
          $('.nav-link').each(function() {
            var linkHref = $(this).attr('href');
            if (linkHref === currentPage) {
              $(this).addClass('active');
            }
          });
          
          // Cerrar el menú al hacer clic en un enlace (en móvil)
          $(".nav-link").click(function() {
            if ($(window).width() <= 992) {
              $("#navContainer").hide();
            }
          });
          
          // Si hay mensajes de sistema, ocultarlos después de 5 segundos
          setTimeout(function() {
            $(".alert").fadeOut(500);
          }, 5000);
        });
      </script>
   </body>
</html>