<?php
session_start();
// Verifica se a variável de sessão "U" está definida
if (!isset($_SESSION["U"])) {
    // Redireciona para a página de login se o usuário não estiver autenticado
    header("location: index.php");
    exit;
}

// Conexão com o banco de dados de usuários
$dbcheckss = new SQLite3("./api/db/studiolivecode_users.db");
$username_check = $_SESSION["U"];
$rescheckss = $dbcheckss->query("SELECT * FROM users WHERE username='" . $username_check . "'");
$rowcheckss = $rescheckss->fetchArray(SQLITE3_ASSOC);

// Verifica se o usuário está autorizado e obtem informações do usuário
if (!$rowcheckss) {
    // Redireciona para a página de login se não encontrar o usuário
    header("location: index.php");
    exit;
}

// Armazena as informações do usuário em variáveis
$name_header = $rowcheckss['name'];
$username_check2 = $rowcheckss["username"];
$logo_header = $rowcheckss['logo'];
$nivel_header = $rowcheckss['nivel'];
$creditos = $rowcheckss['mac_amount'];

// Fecha a conexão com o banco de dados de usuários
$dbcheckss->close();

// Obtém a parte da URL atual
$dircheck = substr($_SERVER["REQUEST_URI"], 0, strrpos($_SERVER["REQUEST_URI"], "/"));
$dircheck2 = substr($dircheck, 1);

// Cria uma variável para verificar a autorização
$valid = $username_check . $dircheck2;

// Verifica se o usuário está autorizado
if (!isset($_SESSION[$valid])) {
    // Redireciona para a página de login se não estiver autorizado
    header("location: index.php");
    exit;
}
$id = $_SESSION['id'];

function initializeDatabase($dbPath, $tableName, $tableStructure) {
    $db = new SQLite3($dbPath);
    $db->exec("CREATE TABLE IF NOT EXISTS $tableName $tableStructure");
    return $db;
}

$dbans = initializeDatabase("./api/db/studiolivecode_clientes.db", "ibo", "(
    id INTEGER PRIMARY KEY NOT NULL,
    mac_address VARCHAR(17),
    username VARCHAR(100),
    password VARCHAR(100),
    expire_date VARCHAR(10),
    dns VARCHAR(100),
    epg_url VARCHAR(100),
    title VARCHAR(100),
    url VARCHAR(100),
    type INTEGER,
    id_user INTEGER,
    active INTEGER
)");

$dbv = initializeDatabase("./api/db/studiolivecode_vencimento.db", "vencimento", "(
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    vencimento TEXT
)");

$resv = $dbv->query("SELECT COUNT(*) as count FROM vencimento");
$rowv = $resv->fetchArray();
$numRowsv = $rowv["count"];
if ($numRowsv == 0) {
    $dbv->exec("INSERT INTO vencimento (id, vencimento) VALUES ('1', '" . date('Y-m-d', strtotime("+32 days")) . "')");
}

$dbans->exec("CREATE TABLE IF NOT EXISTS theme(id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL, name VARCHAR(100), url VARCHAR(100))");
$rows = $dbans->query("SELECT COUNT(*) as count FROM theme");
$rowt = $rows->fetchArray();
$numRowst = $rowt["count"];
if ($numRowst == 0) {
    $dbans->exec("INSERT INTO theme(name,url) VALUES('Default','https://studiolivecode.com.br/assets/front/img/6529ab52dfeaf.png')");
}

$mac_count = $dbans->query("SELECT COUNT(*) as count FROM ibo WHERE id_user = $id");
$mac_count = $mac_count->fetchArray()["count"];
$all_mac_count = $dbans->query("SELECT COUNT(*) as count FROM ibo");
$all_mac_count = $all_mac_count->fetchArray()["count"];

$test_mac_count = $dbans->query("SELECT COUNT(*) as count FROM ibo WHERE active = 0");
$test_mac_count = $test_mac_count->fetchArray()["count"];

$dbpans = new SQLite3("./api/db/studiolivecode_users.db");
$countQuery = "SELECT COUNT(*) as count FROM users WHERE store_type = 1";
$rev_count = $dbpans->querySingle($countQuery);
$resans = $dbpans->query("SELECT * FROM users WHERE ID='$id'");
$rowans = $resans->fetchArray();
$nameans = $rowans["name"];
$logoans = $rowans["logo"];
$nivel_header = $rowans["nivel"];
$nivel_admin = $rowans["admin"];
?>

<!doctype html>
<html lang="en" class="color-sidebar">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--favicon-->
    <link rel="icon" href="assets/images/favicon-32x32.png" type="image/png" />
    <!--plugins-->
    <link href="assets/plugins/simplebar/css/simplebar.css" rel="stylesheet" />
    <link href="assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css" rel="stylesheet" />
    <link href="assets/plugins/metismenu/css/metisMenu.min.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <!-- loader-->
    <link href="assets/css/pace.min.css" rel="stylesheet" />
    <script src="assets/js/pace.min.js"></script>
    <!-- Bootstrap CSS -->
    <link href="assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/bootstrap-extended.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap" rel="stylesheet">
    <link href="assets/css/geral.css" rel="stylesheet">
    <link href="assets/css/icons.css" rel="stylesheet">
    <!-- Theme Style CSS -->
    <link rel="stylesheet" href="assets/css/tema-escuro.css" />
    <link rel="stylesheet" href="assets/css/semi-dark.css" />
    <link rel="stylesheet" href="assets/css/cores-do-menu.css" />
    <link rel="stylesheet" href="assets/css/apps_styles.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-default/default.css" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <title>TOPNET TV</title>
    <meta content="./assets/images/logo.png" property="og:image"/>
</head>

<body>
	<!--wrapper-->
	<div class="wrapper">
		<!--sidebar wrapper -->
		<div class="sidebar-wrapper" data-simplebar="true">
			<div class="sidebar-header">
				<div>
					<img src="assets/images/logo.png" class="logo-icon" alt="logo icon">
				</div>
				<div>
					<h4 class="logo-text">Ibo Pro</h4>
				</div>
				<div class="toggle-icon ms-auto"><i class='bx bx-menu'></i>
				</div>
			</div>
			<!--navigation-->
			<ul class="metismenu" id="menu">
			    <?php if (!is_null($creditos)) : ?>
                    <span>CREDITOS: (<?php echo $creditos;?>)</span>
                <?php endif; ?>
			    <li class="menu-label">Geral</li>
			    <li>				
					<a href="dashboard.php">
						<div class="parent-icon"><i class='bx bxs-dashboard'></i>
						</div>
						<div class="menu-title">Dashboard</div>
					</a>
				</li>
				<li>				
					<a href="https://lojacode.ottgo.top" target="_blank">
						<div class="parent-icon"><i class='bx bxl-android bx-tada'></i>
						</div>
						<div class="menu-title">Aplicativo</div>
					</a>
				</li>
				<li>				
					<a href="loginqr.php" target="_blank">
						<div class="parent-icon"><i class='bx bx-globe bx-spin bx-rotate-90' ></i>
						</div>
						<div class="menu-title">Adicionar via site</div>
					</a>
				</li>
				<li class="menu-label">Cadastros</li>
				<li>
					<a href="users.php">
						<div class="parent-icon"><i class='bx bx-user-circle'></i>
						</div>
						<div class="menu-title">Usuários (<?php echo $mac_count;?>)</div>
					</a>
				</li>
				<li>
					<a href="users_teste.php">
						<div class="parent-icon"><i class='bx bx-user-voice'></i>
						</div>
						<div class="menu-title">Usuários Chatbot (<?php echo $test_mac_count;?>)</div>
					</a>
				</li>
				<?php if($nivel_admin == 1) { ?>
				<li>
					<a href="all_users.php">
						<div class="parent-icon"><i class='bx bxs-user-account'></i>
						</div>
						<div class="menu-title">Todos Usuários (<?php echo $all_mac_count;?>)</div>
					</a>
				</li>
				<li>
				    <a href="revendas.php">
				        <div class="parent-icon"><i class="bx bxs-user-account"></i></div>
				        <div class="menu-title">Revendedores</div>
				    </a>
				</li>
				<li class="menu-label">Design</li>
				<li>				
					<a href="banners.php">
						<div class="parent-icon"><i class='bx bx-images'></i>
						</div>
						<div class="menu-title">Banners</div>
					</a>
				</li>
				<li>				
					<a href="tema.php">
						<div class="parent-icon"><i class='bx bx-palette'></i></i>
						</div>
						<div class="menu-title">Tema</div>
					</a>
				</li>
				<li>
				<li>				
					<a href="logo.php">
						<div class="parent-icon"><i class='bx bx-image'></i>
						</div>
						<div class="menu-title">Logo</div>
					</a>
				</li>
				<li>				
					<a href="bg.php">
						<div class="parent-icon"><i class='bx bx-minus-back'></i>
						</div>
						<div class="menu-title">Fundo</div>
					</a>
				</li>
				<li class="menu-label">Configurações</li>
				<li>
				    <a href="migrar_dns.php">
				        <div class="parent-icon"><i class="bx bx-sitemap"></i>
				        </div>
				        <div class="menu-title">Migrar Servidor</div>
				    </a>
				</li>
				<li>
					<a href="qrcode.php">
						<div class="parent-icon"><i class='bx bx-qr'></i>
						</div>
						<div class="menu-title">QR Code</div>
					</a>
				</li>
				<li>
					<a href="contato.php">
						<div class="parent-icon"><i class='bx bx-phone'></i>
						</div>
						<div class="menu-title">Contato no app</div>
					</a>
				</li>
				<li>
					<a href="sports.php">
						<div class="parent-icon"><i class='bx bx-football'></i>
						</div>
						<div class="menu-title">Guia Esportes</div>
					</a>
				</li>
				<li>
					<a href="note.php">
						<div class="parent-icon"><i class='bx bx-message-detail'></i>
						</div>
						<div class="menu-title">Mensagem no app</div>
					</a>
				</li>
				<li>
					<a href="dns.php">
						<div class="parent-icon"><i class='bx bx-server'></i>
						</div>
						<div class="menu-title">DNS</div>
					</a>
				</li>
				<li>
					<a href="teste.php">
						<div class="parent-icon"><i class='bx bx-bot'></i>
						</div>
						<div class="menu-title">Configuração Teste</div>
					</a>
				</li>
				<?php } ?>
				<li class="menu-label">Usuários</li>
				<li>
					<a href="usuario.php">
						<div class="parent-icon"><i class='bx bx-user' ></i>
						</div>
						<div class="menu-title">Editar Perfil</div>
					</a>
				</li>
				<?php if($nivel_header == 1){?>
				<li>
					<a href="usuarios.php">
						<div class="parent-icon"><i class='bx bx-user' ></i>
						</div>
						<div class="menu-title">Usuários</div>
					</a>
				</li>
				<?php }?>
				<li class="menu-label">Suporte</li>
				<li>
					<a href="https://wa.me/5599991029491" target="_blank">
						<div class="parent-icon"><i class='bx bxl-whatsapp bx-tada bx-rotate-90' ></i>
						</div>
						<div class="menu-title">WhatsApp</div>
					</a>
				</li>
				<?php if($nivel_header == 1){?>
				<li class="menu-label">Vencimento</li>
				<li>
					<a href="vencimento.php">
						<div class="parent-icon"><i class='bx bx-hourglass' ></i>
						</div>
						<div class="menu-title">Vencimento</div>
					</a>
				</li>
				<?php }?>
				<li class="menu-label">Sair</li>
				<li>
					<a href="sair.php">
						<div class="parent-icon"><i class='bx bx-exit' ></i>
						</div>
						<div class="menu-title">Sair</div>
					</a>
				</li>
			<!--end navigation-->
		</div>
		<!--end sidebar wrapper -->
		<!--start header -->
		<header>
			<div class="topbar d-flex align-items-center">
				<nav class="navbar navbar-expand">
					<div class="mobile-toggle-menu"><i class='bx bx-menu'></i>
					</div>
					
					<div class="marquee">
    <div class="marquee-content">
        <span id="vencimento-text"></span>
    </div>
</div>
					<div class="top-menu ms-auto">
						<ul class="navbar-nav align-items-center">
							
							<li class="nav-item dropdown dropdown-large">
								<a class="nav-link dropdown-toggle dropdown-toggle-nocaret" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">	<i class='bx bx-category'></i>
								</a>
								<div class="dropdown-menu dropdown-menu-end">
									<div class="row row-cols-3 g-3 p-3">
									    <div class="col text-center">
											<a href='dashboard.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bxs-dashboard'></i>
											</div></a>
											<div class="app-title">Dashboard</div>
										</div>
										<div class="col text-center">
											<a href='loginqr.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-globe'></i>
											</div></a>
											<div class="app-title">Adicionar via site</div>
										</div>
										<div class="col text-center">
											<a href='users.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-user-check'></i>
											</div></a>
											<div class="app-title">Usuários</div>
										</div>
										<div class="col text-center">
											<a href='users_teste.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-user-check'></i>
											</div></a>
											<div class="app-title">Usuários ChatBot</div>
										</div>
										<?php if($nivel_admin == 1){?>
										<div class="col text-center">
											<a href='all_users.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-user-check'></i>
											</div></a>
											<div class="app-title">Todos Usuários</div>
										</div>
										<div class="col text-center">
											<a href='banners.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-images'></i>
											</div></a>
											<div class="app-title">Banner</div>
										</div>
										<div class="col text-center">
											<a href='tema.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-palette'></i>
											</div></a>
											<div class="app-title">Tema</div>
										</div>
										<div class="col text-center">
											<a href='logo.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-image'></i>
											</div></a>
											<div class="app-title">Logo</div>
										</div>
										<div class="col text-center">
											<a href='bg.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-image'></i>
											</div></a>
											<div class="app-title">Fundo</div>
										</div>
										<div class="col text-center">
											<a href='qrcode.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-qr'></i>
											</div></a>
											<div class="app-title">QR Code</div>
										</div>
										<div class="col text-center">
											<a href='contato.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-phone'></i>
											</div></a>
											<div class="app-title">Contato no app</div>
										</div>
										<div class="col text-center">
											<a href='sports.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-football'></i>
											</div></a>
											<div class="app-title">Guia Esportes</div>
										</div>
										<div class="col text-center">
											<a href='note.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-message-detail'></i>
											</div></a>
											<div class="app-title">Mensagem no app</div>
										</div>
										<div class="col text-center">
											<a href='dns.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-server'></i>
											</div></a>
											<div class="app-title">DNS</div>
										</div>
										<div class="col text-center">
											<a href='teste.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-bot'></i>
											</div></a>
											<div class="app-title">Configuração Teste</div>
										</div>
										<?php }?>
										<div class="col text-center">
											<a href='https://wa.me/554112345678'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-message'></i>
											</div></a>
											<div class="app-title">Suporte</div>
										</div>
										<?php if($nivel_header == 1){?>
										<div class="col text-center">
											<a href='usuarios.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-user'></i>
											</div></a>
											<div class="app-title">Usuários</div>
										</div>
										<div class="col text-center">
											<a href='vencimento.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-hourglass'></i>
											</div></a>
											<div class="app-title">Vencimento</div>
										</div>
										<?php }?>
										<div class="col text-center">
											<a href='sair.php'><div class="app-box mx-auto bg-gradient-cosmic text-white"><i class='bx bx-exit'></i>
											</div></a>
											<div class="app-title">Sair</div>
										</div>
									</div>
								</div>
							</li>
							<li class="nav-item dropdown dropdown-large">
								
								<div class="dropdown-menu dropdown-menu-end">
									
									<div class="header-notifications-list">
										
									</div>
									<a href="javascript:;">
										<div class="text-center msg-footer">View All Notifications</div>
									</a>
								</div>
							</li>
							<li class="nav-item dropdown dropdown-large">
								
								<div class="dropdown-menu dropdown-menu-end">
									
									<div class="header-message-list">
										
									</div>
									<a href="javascript:;">
										<div class="text-center msg-footer">View All Messages</div>
									</a>
								</div>
							</li>
						</ul>
					</div>
					
				</nav>
			</div>
		</header>
		<script>
            document.addEventListener("DOMContentLoaded", function() {
                var vencimentoText = document.getElementById('vencimento-text');
                <?php
                $resv = $dbv->query("SELECT vencimento FROM vencimento WHERE id='1'");
                $rowv = $resv->fetchArray();
                $vencimento = $rowv["vencimento"];
        
                // Calcula o número de dias restantes
                $dataAtual = new DateTime();
                $dataVencimento = new DateTime($vencimento);
                $diasRestantes = $dataAtual->diff($dataVencimento)->format('%r%a');
        
                if ($diasRestantes <= 0) {
                    echo 'vencimentoText.innerHTML = "SEU PAINEL ESTÁ VENCIDO! APLICATIVO DESATIVADO!";';
                } else {
                    echo 'vencimentoText.innerHTML = "PAINEL VENCE EM '.$diasRestantes.' DIAS!";';
                }
                ?>
            });
        </script>
		<!--end header -->
<div class="page-wrapper">
<div class="page-content">