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

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

if (!isset($_SESSION['name']) || $_SESSION['name'] != $loggedinuser) {
	header("location:index.php");
	exit();
}

if (isset($_REQUEST['logout'])) {
	session_destroy();
	setcookie("auth", "");
	header("Location: index.php");
	exit;
}

$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;

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

$current_page = basename($_SERVER["SCRIPT_NAME"]);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title><?php echo isset($config_ini['panel_name']) ? htmlspecialchars($config_ini['panel_name']) : 'Panel'; ?></title>
  <link rel="icon" type="image/x-icon" href="./img/favicon.ico">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" crossorigin="anonymous">
  <style>
    :root {
      --yt-red: #ff0000;
      --yt-dark: #0f0f0f;
      --yt-surface: #212121;
      --yt-surface2: #2d2d2d;
      --yt-surface3: #3d3d3d;
      --yt-text: #f1f1f1;
      --yt-text-muted: #aaaaaa;
      --yt-border: #3d3d3d;
      --yt-hover: #272727;
      --yt-blue: #3ea6ff;
      --yt-green: #27cc7f;
      --sidebar-w: 240px;
      --topbar-h: 56px;
    }
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    html, body {
      font-family: 'Roboto', sans-serif;
      background: var(--yt-dark);
      color: var(--yt-text);
      min-height: 100vh;
    }

    /* ── TOPBAR ── */
    .yt-topbar {
      position: fixed; top: 0; left: 0; right: 0;
      height: var(--topbar-h);
      background: var(--yt-dark);
      border-bottom: 1px solid #1a1a1a;
      display: flex; align-items: center; justify-content: space-between;
      padding: 0 12px; z-index: 200;
    }
    .yt-topbar-left { display: flex; align-items: center; gap: 8px; }
    .yt-menu-btn {
      background: none; border: none; color: var(--yt-text);
      font-size: 18px; cursor: pointer; padding: 8px;
      border-radius: 50%; transition: background .15s; width:40px; height:40px;
      display:flex; align-items:center; justify-content:center; flex-shrink:0;
    }
    .yt-menu-btn:hover { background: var(--yt-surface); }
    .yt-logo { display: flex; align-items: center; text-decoration: none; }
    .yt-logo img { height: 32px; width: auto; object-fit: contain; }

    /* Search */
    .yt-search-wrap { display:flex; flex:1; max-width:420px; margin:0 12px; }
    .yt-search-inner {
      display:flex; flex:1;
      border: 1px solid var(--yt-border); border-radius: 40px 0 0 40px;
      background: var(--yt-surface); overflow:hidden;
    }
    .yt-search-inner input {
      flex:1; background:transparent; border:none; outline:none;
      color:var(--yt-text); font-size:14px; padding:8px 14px;
      font-family:'Roboto',sans-serif; min-width:0;
    }
    .yt-search-inner input::placeholder { color: var(--yt-text-muted); }
    .yt-search-btn {
      background: var(--yt-surface2); border: 1px solid var(--yt-border);
      border-left: none; color: var(--yt-text); padding: 0 16px;
      border-radius: 0 40px 40px 0; cursor: pointer; font-size:14px;
      height: 38px; transition: background .15s; flex-shrink:0;
    }
    .yt-search-btn:hover { background: var(--yt-surface3); }

    /* Top right */
    .yt-topbar-right { display:flex; align-items:center; gap:6px; flex-shrink:0; }
    .yt-logout {
      display:flex; align-items:center; gap:6px;
      background:none; border:1px solid var(--yt-border); color:var(--yt-text-muted);
      padding:6px 12px; border-radius:20px; font-size:13px; font-family:'Roboto',sans-serif;
      text-decoration:none; transition:all .15s; cursor:pointer; white-space:nowrap;
    }
    .yt-logout:hover { border-color:var(--yt-red); color:var(--yt-red); background:rgba(255,0,0,.08); }
    .yt-logout span { display:inline; }
    .yt-avatar {
      width:32px; height:32px; border-radius:50%;
      background:var(--yt-red); color:#fff;
      display:flex; align-items:center; justify-content:center;
      font-weight:700; font-size:14px; cursor:pointer; flex-shrink:0;
    }

    /* ── SIDEBAR ── */
    .yt-sidebar {
      position:fixed; top:var(--topbar-h); left:0; bottom:0;
      width:var(--sidebar-w); background:var(--yt-dark);
      padding:12px 0; overflow-y:auto; z-index:150;
      transition:transform .25s; scrollbar-width:thin;
      scrollbar-color: var(--yt-surface3) transparent;
    }
    .yt-sidebar::-webkit-scrollbar { width:4px; }
    .yt-sidebar::-webkit-scrollbar-thumb { background:var(--yt-surface3); border-radius:4px; }

    /* Overlay mobile */
    .yt-overlay {
      display:none; position:fixed; inset:0;
      background:rgba(0,0,0,.6); z-index:140;
    }
    .yt-overlay.show { display:block; }

    .yt-nav-item {
      display:flex; align-items:center; gap:22px;
      padding:12px 20px; margin:0 8px; border-radius:10px;
      text-decoration:none; color:var(--yt-text); font-size:14px;
      transition:background .15s; cursor:pointer;
    }
    .yt-nav-item:hover { background:var(--yt-hover); color:var(--yt-text); }
    .yt-nav-item.active { background:var(--yt-surface2); font-weight:500; }
    .yt-nav-item i { font-size:18px; width:20px; text-align:center; flex-shrink:0; }
    .yt-nav-divider { height:1px; background:var(--yt-border); margin:10px 0; }
    .yt-nav-section { font-size:13px; font-weight:500; padding:8px 20px 4px; color:var(--yt-text-muted); }

    /* ── MAIN ── */
    .yt-main {
      margin-left:var(--sidebar-w);
      margin-top:var(--topbar-h);
      padding:24px 24px;
      min-height:calc(100vh - var(--topbar-h));
      transition:margin-left .25s;
    }

    /* ── PAGE HEADER ── */
    .yt-page-header {
      display:flex; align-items:center; justify-content:space-between;
      margin-bottom:20px; flex-wrap:wrap; gap:12px;
    }
    .yt-page-title { display:flex; align-items:center; gap:10px; }
    .yt-page-title h1 { font-size:18px; font-weight:500; }
    .yt-badge {
      background:var(--yt-surface2); color:var(--yt-text-muted);
      font-size:12px; padding:2px 10px; border-radius:20px;
    }

    /* ── BUTTONS ── */
    .yt-btn-red {
      display:inline-flex; align-items:center; gap:8px;
      background:var(--yt-red); color:#fff; border:none;
      padding:9px 18px; border-radius:20px;
      font-family:'Roboto',sans-serif; font-size:14px; font-weight:500;
      cursor:pointer; text-decoration:none; transition:background .15s, transform .1s;
      white-space:nowrap;
    }
    .yt-btn-red:hover { background:#cc0000; color:#fff; }
    .yt-btn-red:active { transform:scale(.97); }

    .yt-btn-ghost {
      display:inline-flex; align-items:center; gap:8px;
      background:var(--yt-surface2); color:var(--yt-text);
      border:1px solid var(--yt-border);
      padding:9px 18px; border-radius:20px;
      font-family:'Roboto',sans-serif; font-size:14px;
      cursor:pointer; text-decoration:none; transition:background .15s;
      white-space:nowrap;
    }
    .yt-btn-ghost:hover { background:var(--yt-surface3); color:var(--yt-text); }

    /* ── CARD ── */
    .yt-card {
      background:var(--yt-surface); border:1px solid var(--yt-border);
      border-radius:12px; overflow:hidden; margin-bottom:20px;
    }
    .yt-card-header {
      display:flex; align-items:center; justify-content:space-between;
      padding:14px 20px; border-bottom:1px solid var(--yt-border);
      flex-wrap:wrap; gap:8px;
    }
    .yt-card-title { font-size:14px; font-weight:500; display:flex; align-items:center; gap:10px; }
    .yt-card-title i { color:var(--yt-red); }
    .yt-card-body { padding:20px; }

    /* ── TABLE ── */
    .yt-table-wrap { overflow-x:auto; -webkit-overflow-scrolling:touch; }
    .yt-table { width:100%; border-collapse:collapse; min-width:400px; }
    .yt-table thead th {
      padding:10px 16px; text-align:left;
      font-size:11px; font-weight:500; color:var(--yt-text-muted);
      text-transform:uppercase; letter-spacing:.6px;
      border-bottom:1px solid var(--yt-border);
      white-space:nowrap;
    }
    .yt-table tbody tr { border-bottom:1px solid #1f1f1f; transition:background .12s; }
    .yt-table tbody tr:last-child { border-bottom:none; }
    .yt-table tbody tr:hover { background:var(--yt-hover); }
    .yt-table tbody td { padding:12px 16px; font-size:14px; vertical-align:middle; }

    .yt-dns-badge {
      font-family:monospace; font-size:12px; color:var(--yt-blue);
      background:rgba(62,166,255,.08); display:inline-block;
      padding:3px 8px; border-radius:6px; border:1px solid rgba(62,166,255,.2);
      word-break:break-all;
    }
    .yt-pass-badge {
      font-family:monospace; font-size:12px; color:#aaa;
      background:var(--yt-surface2); display:inline-block;
      padding:3px 8px; border-radius:6px;
    }
    .yt-expire-badge {
      font-size:12px; padding:3px 10px; border-radius:20px; display:inline-block; white-space:nowrap;
    }
    .yt-expire-ok { background:rgba(39,204,127,.1); color:var(--yt-green); border:1px solid rgba(39,204,127,.2); }
    .yt-expire-warn { background:rgba(255,180,0,.1); color:#ffb400; border:1px solid rgba(255,180,0,.2); }
    .yt-expire-over { background:rgba(255,0,0,.1); color:var(--yt-red); border:1px solid rgba(255,0,0,.2); }

    .yt-act-wrap { display:flex; gap:6px; }
    .yt-act-btn {
      width:32px; height:32px; border-radius:8px;
      border:1px solid var(--yt-border); background:none;
      color:var(--yt-text-muted); display:flex; align-items:center; justify-content:center;
      cursor:pointer; font-size:13px; text-decoration:none; transition:all .15s;
    }
    .yt-act-btn:hover { background:var(--yt-surface2); color:var(--yt-text); border-color:var(--yt-text-muted); }
    .yt-act-btn.danger:hover { background:rgba(255,0,0,.1); color:var(--yt-red); border-color:var(--yt-red); }

    /* ── FORM ── */
    .yt-form-grid { display:grid; grid-template-columns:1fr 1fr; gap:16px; }
    .yt-form-group { display:flex; flex-direction:column; gap:6px; }
    .yt-form-group.full { grid-column:1/-1; }
    .yt-form-group label {
      font-size:12px; font-weight:500; color:var(--yt-text-muted);
      text-transform:uppercase; letter-spacing:.5px;
    }
    .yt-form-group input, .yt-form-group select {
      background:var(--yt-surface2); border:1px solid var(--yt-border);
      border-radius:8px; color:var(--yt-text);
      padding:11px 14px; font-family:'Roboto',sans-serif; font-size:14px;
      outline:none; transition:border-color .15s; width:100%;
    }
    .yt-form-group input:focus, .yt-form-group select:focus { border-color:var(--yt-red); }
    .yt-form-group input::placeholder { color:var(--yt-text-muted); }
    .yt-form-group input[type="date"]::-webkit-calendar-picker-indicator { filter:invert(1); }
    .yt-form-footer { display:flex; gap:12px; justify-content:flex-end; margin-top:8px; flex-wrap:wrap; }

    /* ── MODAL ── */
    #confirm-delete .modal-content, #confirm-reset .modal-content {
      background:var(--yt-surface) !important;
      border:1px solid var(--yt-border); border-radius:16px; color:var(--yt-text);
    }
    #confirm-delete .modal-header, #confirm-reset .modal-header { border-bottom:1px solid var(--yt-border); }
    #confirm-delete .modal-footer, #confirm-reset .modal-footer { border-top:1px solid var(--yt-border); }
    #confirm-delete h2, #confirm-reset h2 { color:var(--yt-text) !important; font-size:16px; }

    /* ── TOAST ── */
    .yt-toast {
      position:fixed; bottom:20px; left:50%;
      transform:translateX(-50%) translateY(80px);
      background:var(--yt-surface2); border:1px solid var(--yt-border);
      color:var(--yt-text); padding:10px 20px; border-radius:8px;
      font-size:14px; z-index:9999; transition:transform .3s;
      display:flex; align-items:center; gap:10px;
      max-width:90vw; text-align:center;
    }
    .yt-toast.show { transform:translateX(-50%) translateY(0); }
    .yt-toast i { color:var(--yt-green); flex-shrink:0; }
    .yt-toast.error i { color:var(--yt-red); }

    /* ── EMPTY STATE ── */
    .yt-empty { text-align:center; padding:48px 20px; color:var(--yt-text-muted); }
    .yt-empty i { font-size:40px; margin-bottom:12px; display:block; }
    .yt-empty p { font-size:14px; }

    /* ── STATS ── */
    .yt-stats { display:grid; grid-template-columns:repeat(auto-fit,minmax(140px,1fr)); gap:12px; margin-bottom:20px; }
    .yt-stat {
      background:var(--yt-surface); border:1px solid var(--yt-border);
      border-radius:12px; padding:14px 16px;
      display:flex; align-items:center; gap:12px;
    }
    .yt-stat-icon {
      width:40px; height:40px; border-radius:10px;
      display:flex; align-items:center; justify-content:center; font-size:17px; flex-shrink:0;
    }
    .yt-stat-icon.red { background:rgba(255,0,0,.12); color:var(--yt-red); }
    .yt-stat-icon.blue { background:rgba(62,166,255,.12); color:var(--yt-blue); }
    .yt-stat-icon.green { background:rgba(39,204,127,.12); color:var(--yt-green); }
    .yt-stat-icon.yellow { background:rgba(255,180,0,.12); color:#ffb400; }
    .yt-stat-info span { font-size:11px; color:var(--yt-text-muted); display:block; margin-bottom:2px; }
    .yt-stat-info strong { font-size:18px; font-weight:700; }

    /* scrollbar */
    ::-webkit-scrollbar { width:6px; height:6px; }
    ::-webkit-scrollbar-track { background:transparent; }
    ::-webkit-scrollbar-thumb { background:var(--yt-surface3); border-radius:4px; }

    /* ── MOBILE ── */
    @media (max-width: 768px) {
      /* Sidebar escondida por padrão no mobile */
      .yt-sidebar { transform: translateX(-100%); }

      /* Main ocupa tela toda */
      .yt-main { margin-left: 0 !important; padding: 16px; }

      /* Search some no mobile, fica só no menu */
      .yt-search-wrap { display: none; }

      /* Logout só ícone no mobile */
      .yt-logout span { display: none; }
      .yt-logout { padding: 6px 10px; }

      /* Logo menor */
      .yt-logo img { height: 28px; }

      /* Stats 2 colunas */
      .yt-stats { grid-template-columns: repeat(2, 1fr); }

      /* Form 1 coluna */
      .yt-form-grid { grid-template-columns: 1fr; }

      /* Page header empilha */
      .yt-page-header { flex-direction: column; align-items: flex-start; }

      /* Botões menores */
      .yt-btn-red, .yt-btn-ghost { font-size: 13px; padding: 8px 14px; }

      /* Tabela scroll horizontal */
      .yt-table-wrap { overflow-x: auto; }
    }

    @media (max-width: 400px) {
      .yt-stats { grid-template-columns: 1fr 1fr; }
      .yt-topbar { padding: 0 8px; }
    }
  </style>
</head>
<body>

<!-- OVERLAY mobile -->
<div class="yt-overlay" id="ytOverlay" onclick="ytCloseSidebar()"></div>

<!-- TOPBAR -->
<header class="yt-topbar">
  <div class="yt-topbar-left">
    <button class="yt-menu-btn" onclick="ytToggleSidebar()" title="Menu">
      <i class="fas fa-bars"></i>
    </button>
    <a href="main.php" class="yt-logo">
      <img src="./img/ytp.jpg" alt="Logo">
    </a>
  </div>

  <div class="yt-search-wrap">
    <div class="yt-search-inner">
      <input type="text" id="ytSearchInput" placeholder="Pesquisar...">
    </div>
    <button class="yt-search-btn" onclick="ytSearchTable()"><i class="fas fa-search"></i></button>
  </div>

  <div class="yt-topbar-right">
    <a href="<?= basename($_SERVER["SCRIPT_NAME"]) . '?logout' ?>" class="yt-logout" title="Sair">
      <i class="fas fa-sign-out-alt"></i><span> Sair</span>
    </a>
    <div class="yt-avatar"><?php echo strtoupper(substr($loggedinuser ?? 'A', 0, 1)); ?></div>
  </div>
</header>

<!-- SIDEBAR -->
<nav class="yt-sidebar" id="ytSidebar">
  <a href="main.php" class="yt-nav-item <?= $current_page === 'main.php' ? 'active' : '' ?>">
    <i class="fas fa-server"></i> DNS SERVIDOR
  </a>
  <a href="adduser.php" class="yt-nav-item <?= $current_page === 'adduser.php' ? 'active' : '' ?>">
    <i class="fas fa-users"></i> USUARIOS
  </a>
  <a href="user.php" class="yt-nav-item <?= $current_page === 'user.php' ? 'active' : '' ?>">
    <i class="fas fa-user-cog"></i> CREDENCIAIS
  </a>
  <div class="yt-nav-divider"></div>
  <div class="yt-nav-section">Sistema</div>
  <a href="<?= basename($_SERVER["SCRIPT_NAME"]) . '?logout' ?>" class="yt-nav-item">
    <i class="fas fa-sign-out-alt"></i> Sair
  </a>
</nav>

<!-- MAIN WRAPPER -->
<div class="yt-main" id="ytMain">

<!-- TOAST -->
<div class="yt-toast" id="ytToast"><i class="fas fa-check-circle"></i><span id="ytToastMsg"></span></div>

<?php
if (isset($_GET['status'])) {
  $msg = $_GET['status'] == 1 ? 'Operação realizada com sucesso!' : 'Registro excluído!';
  echo "<script>document.addEventListener('DOMContentLoaded',function(){ ytShowToast(" . json_encode($msg) . "); });</script>";
}
?>

<script>
const isMobile = () => window.innerWidth <= 768;
let ytSidebarOpen = !isMobile();

function ytToggleSidebar() {
  const s = document.getElementById('ytSidebar');
  const m = document.getElementById('ytMain');
  const o = document.getElementById('ytOverlay');
  ytSidebarOpen = !ytSidebarOpen;
  if (ytSidebarOpen) {
    s.style.transform = 'translateX(0)';
    if (!isMobile()) m.style.marginLeft = 'var(--sidebar-w)';
    if (isMobile()) o.classList.add('show');
  } else {
    s.style.transform = 'translateX(-240px)';
    m.style.marginLeft = '0';
    o.classList.remove('show');
  }
}

function ytCloseSidebar() {
  const s = document.getElementById('ytSidebar');
  const m = document.getElementById('ytMain');
  const o = document.getElementById('ytOverlay');
  ytSidebarOpen = false;
  s.style.transform = 'translateX(-240px)';
  if (!isMobile()) m.style.marginLeft = '0';
  o.classList.remove('show');
}

// Fecha sidebar ao redimensionar para desktop
window.addEventListener('resize', () => {
  if (!isMobile() && ytSidebarOpen) {
    document.getElementById('ytMain').style.marginLeft = 'var(--sidebar-w)';
    document.getElementById('ytOverlay').classList.remove('show');
  }
});

function ytShowToast(msg, isError) {
  const t = document.getElementById('ytToast');
  const i = t.querySelector('i');
  document.getElementById('ytToastMsg').textContent = msg;
  t.classList.toggle('error', !!isError);
  i.className = isError ? 'fas fa-exclamation-circle' : 'fas fa-check-circle';
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3500);
}

function ytSearchTable() {
  const q = document.getElementById('ytSearchInput').value.toLowerCase();
  document.querySelectorAll('.yt-table tbody tr').forEach(tr => {
    tr.style.display = tr.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
}

document.addEventListener('keyup', function(e) {
  if (document.activeElement.id === 'ytSearchInput') ytSearchTable();
});
</script>
