<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('../a/.eggziedb.db');
$db->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL,mac_address VARCHAR(100),username VARCHAR(100),password VARCHAR(100),expire_date VARCHAR(100),url VARCHAR(100),title VARCHAR(100),created_at VARCHAR(100))');
$res = $db->query('SELECT * FROM ibo');

if(isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = ""; // Default value
}

include '../includes/header3.php';

if (isset($_POST['submit'])) {
    
     $meses = $_POST['expire_date'];
     $db1 = new SQLite3('../a/.eggziedb.db');
     $result = $db1->query("SELECT macs FROM sub_revenda WHERE usuario = '$seller_name'");
     // Iterate over the fetched results
     while ($row = $result->fetchArray()) {
         // Output the value of the column
         $macs = $row['macs'];
         break;
     }
     
     if($macs < $meses) {
        echo "<script>alert('Você não possui MACs suficientes!');window.location.href='index.php';</script>";
     } else {
         
             $usuario =  $_POST['username'];
             $mac_address = strtoupper($_POST['mac_address']);
             //$result = $db1->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_address'");
            $row = $result->fetchArray(SQLITE3_ASSOC);
            $count = $row['count'];
        
            if($count || $usuario == "ADM") {
              echo "<script>alert('Já existe um usuario registrado com esse MAC que você esta tentando, por favor escolha outro!');window.location.href='index.php';</script>";
            } else {
                if($meses <= 0 || $meses > 999) {
                     echo "<script>alert('Numero de meses invalido!');window.location.href='index.php';</script>";
                } else {
                    $currentDate = date('Y-m-d');
                    // Add 5 months
                    $ne = date('Y-m-d', strtotime("+$meses years", strtotime($currentDate)));
                	$start = date('Y-m-d');
                	$end = date('h:m:s');
                	$full = $start . 'T' . $end . '.000000Z';
                	$db1->exec('INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, seller, extra) VALUES(\'' . strtoupper($_POST['mac_address']) . '\', \'' . $_POST['username'] . '\', \'' . $_POST['password'] . '\', \'' . $ne . '\', \'' . $_POST['dns'] . '\', \'' . $_POST['title'] . '\',\'' . $full . '\',\'' . $seller_name . '\', \''.$_POST['Descricao'].'\')');
                	$newmac = $macs - $meses;
                	$db1->exec("UPDATE sub_revenda SET macs = '$newmac' WHERE usuario = '$seller_name'");
                	$db1->close();
                    echo "<script>window.location.href='index.php';</script>";
                }
            }
     }
}

$playlistNames = [
    'Ultimate Entertainment',
    'Global TV Hub',
    'Prime Streaming Zone',
    'All-in-One IPTV Lounge',
    'HD Channel Showcase',
    'Sports Mania',
    'Movie Magic',
    'News Network Central',
    'Kids Fun Zone',
    'Lifestyle Paradise',
    'Documentary Delight',
    'Music Melodies',
    'Comedy Central',
    'Reality TV Extravaganza',
    'Traveler\'s Guide',
    'Sci-Fi Spectacle',
    'Health and Fitness Channel',
    'Gaming Galaxy',
    'Fashion Forward',
    'Business Buzz',
    'Foodie Haven',
    'Educational Excellence',
    'Thriller Theater',
    'History Channel Vault',
    'Cartoons Unlimited',
    'Tech Titans',
    'Wildlife Adventure',
    'Artistic Expressions',
    'Supernatural Secrets',
    'Retro Rewind',
    'Romance Reels',
    'Spiritual Serenity',
    'DIY Network',
    'Car Enthusiast\'s Paradise',
    'Action Packed',
    'True Crime Stories',
    'International Flavor',
    'Nature\'s Wonders',
    'Home Makeover Madness',
    'Anime Haven',
    'Pop Culture Playground',
    'Hidden Gems',
    'Blockbuster Bonanza',
    'Motivational Mojo',
    'Vintage Vibes',
    'Outdoor Expeditions',
    'Social Media Stars',
    'Celebrity Showcase',
    'Science and Technology Marvels',
    'Fitness Freaks'
];

$randomPlaylistName = $playlistNames[array_rand($playlistNames)];

?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var macAddressInput = document.getElementById("mac_address");

    macAddressInput.addEventListener("input", function(e) {
        var value = e.target.value;
        value = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();

        var formattedValue = "";
        for (var i = 0; i < value.length; i++) {
            formattedValue += value[i];
            if ((i + 1) % 2 === 0 && i < value.length - 1) {
                formattedValue += ":";
            }
        }

        e.target.value = formattedValue;
    });
});
</script>
<script>
function extract(event) {
  event.preventDefault(); // Prevent page refresh

  var m3uLink = document.getElementById("m3u_address").value;

  // Extract server URL
  var serverUrl = m3uLink.split("/get.php")[0];
  document.getElementById("server_url").value = serverUrl;

  // Extract username
  var username = getParameterByName("username", m3uLink);
  document.getElementById("username").value = username;

  // Extract password
  var password = getParameterByName("password", m3uLink);
  document.getElementById("password").value = password;
}

function getParameterByName(name, url) {
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return "";
  if (!results[2]) return "";
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

<style>
/* =========================================================
   VISUAL CYBERPUNK (somente CSS / visual)
========================================================= */
:root{
  --neon-cyan:#00f2ff;
  --neon-purple:#bc13fe;
  --neon-pink:#ff2bd6;
  --danger:#ff4b2b;

  --glass: rgba(255,255,255,.08);
  --stroke: rgba(255,255,255,.14);
  --stroke2: rgba(255,255,255,.10);
  --text: rgba(255,255,255,.92);
  --muted: rgba(255,255,255,.68);

  --r-lg: 18px;
  --r-md: 14px;
  --shadow: 0 18px 60px rgba(0,0,0,.55);
}

/* remove o cinza do SB Admin por trás */
#content-wrapper, #content, .container-fluid{ background: transparent !important; }

/* header do conteúdo */
.page-title{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
  margin-bottom: 14px;
}
.page-title h1{
  margin:0;
  font-family:'Orbitron',sans-serif;
  letter-spacing:.06em;
  color: rgba(0,242,255,.92);
  text-shadow: 0 0 14px rgba(0,242,255,.18);
}
.page-sub{
  color: var(--muted);
  font-size: 13px;
}

/* grid dos cards */
.grid-wrap{
  display:grid;
  grid-template-columns: 1fr;
  gap: 16px;
}
@media (min-width: 992px){
  .grid-wrap{ grid-template-columns: 1fr 1fr; }
}

/* cards cyberpunk */
.cp-card{
  background: linear-gradient(180deg, rgba(255,255,255,.12), rgba(255,255,255,.04)) !important;
  border: 1px solid var(--stroke) !important;
  border-radius: var(--r-lg) !important;
  box-shadow: var(--shadow) !important;
  backdrop-filter: blur(16px);
  -webkit-backdrop-filter: blur(16px);
  overflow:hidden;
  position:relative;
}

.cp-card::before{
  content:"";
  position:absolute;
  inset:-55% -35%;
  background: linear-gradient(120deg, transparent 35%, rgba(255,255,255,.08) 45%, transparent 58%);
  transform: rotate(12deg);
  opacity:.65;
  pointer-events:none;
}

.cp-card .cp-head{
  padding: 14px 16px;
  border-bottom: 1px solid var(--stroke2);
  background: linear-gradient(90deg, rgba(0,242,255,.10), rgba(188,19,254,.06), rgba(255,43,214,.05));
  position:relative;
  z-index:1;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
}

.cp-head .cp-title{
  margin:0;
  font-family:'Orbitron',sans-serif;
  letter-spacing:.06em;
  text-transform: uppercase;
  font-size: 13px;
  color: rgba(255,255,255,.92);
  display:flex;
  align-items:center;
  gap:10px;
}
.cp-head .cp-title i{
  color: rgba(0,242,255,.92);
  text-shadow: 0 0 14px rgba(0,242,255,.20);
}

.cp-card .cp-body{
  padding: 16px;
  position:relative;
  z-index:1;
}

/* inputs */
.form-control{
  background: rgba(0,0,0,.30) !important;
  border: 1px solid rgba(255,255,255,.14) !important;
  color: var(--text) !important;
  border-radius: 14px !important;
  box-shadow: none !important;
}
.form-control::placeholder{ color: rgba(255,255,255,.45) !important; }
label{ color: rgba(255,255,255,.86) !important; }

/* input-group com botão colado */
.input-group .form-control{
  border-top-right-radius: 0 !important;
  border-bottom-right-radius: 0 !important;
}
.input-group .btn{
  border-top-left-radius: 0 !important;
  border-bottom-left-radius: 0 !important;
}

/* botões no padrão cyberpunk */
.btn{
  border-radius: 999px !important;
  font-family:'Orbitron',sans-serif;
  letter-spacing:.06em;
  text-transform: uppercase;
  font-weight: 900 !important;
}
.btn-success{
  background: rgba(0,242,255,.10) !important;
  border: 1px solid rgba(0,242,255,.35) !important;
  color: rgba(255,255,255,.92) !important;
  box-shadow: 0 0 22px rgba(0,242,255,.12) !important;
}
.btn-success:hover{
  background: rgba(0,242,255,.16) !important;
  transform: translateY(-1px);
  box-shadow: 0 0 34px rgba(0,242,255,.18) !important;
}
.btn-icon-split .icon{
  background: transparent !important;
}

/* badges informativos */
.cp-hint{
  margin-top: 10px;
  display:inline-flex;
  align-items:center;
  gap:10px;
  padding: 10px 12px;
  border-radius: 14px;
  background: rgba(0,0,0,.28);
  border: 1px solid rgba(255,255,255,.12);
  color: rgba(255,255,255,.82);
  font-size: 12px;
}
.cp-hint i{
  color: var(--neon-purple);
  text-shadow: 0 0 14px rgba(188,19,254,.18);
}

/* alerta de consumo */
#gasto{
  display:inline-flex;
  align-items:center;
  gap:10px;
  margin-top: 12px;
  padding: 10px 12px;
  border-radius: 999px;
  border: 1px solid rgba(255,75,43,.45);
  background: rgba(255,75,43,.10);
  color: rgba(255,255,255,.92) !important;
  font-family:'Orbitron',sans-serif;
  letter-spacing:.04em;
  font-size: 12px;
}

/* títulos pequenos dentro do form */
.cp-label-strong{
  font-family:'Orbitron',sans-serif;
  letter-spacing:.06em;
  text-transform: uppercase;
  font-size: 12px;
  color: rgba(0,242,255,.90);
}

/* organiza o formulário melhor */
.cp-row{
  display:grid;
  grid-template-columns: 1fr;
  gap: 12px;
}
@media (min-width: 1200px){
  .cp-row{ grid-template-columns: 1fr 1fr; }
}

/* deixa botões com altura padrão */
.cp-actions .btn{
  height: 44px;
  padding: 0 18px !important;
  display:inline-flex;
  align-items:center;
  justify-content:center;
}

/* separador */
.cp-divider{
  height:1px;
  background: rgba(255,255,255,.10);
  margin: 14px 0;
}

/* H1 antigo do SB */
.text-gray-800{ color: rgba(255,255,255,.88) !important; }
</style>

<div class="container-fluid" style="padding-top: 10px; padding-bottom: 30px;">

  <div class="page-title">
    <div>
      <h1 class="h3">Ativar Usuário</h1>
      <div class="page-sub">Mantenha o padrão do painel: neon, vidro e organização por blocos.</div>
    </div>
  </div>

  <div class="grid-wrap">

    <!-- CARD 1: M3U Extractor -->
    <div class="cp-card">
      <div class="cp-head">
        <h6 class="cp-title"><i class="fas fa-magic"></i> M3U Extractor</h6>
      </div>
      <div class="cp-body">
        <form>
          <div class="form-group mb-0">
            <label class="control-label cp-label-strong" for="m3u_address">Link M3U</label>
            <div class="input-group">
              <input class="form-control" id="m3u_address" name="m3u_address" placeholder="Cole aqui o link M3U..." type="text" required/>
              <button class="btn btn-success btn-icon-split" id="extract_button" onclick="extract(event)">
                <span class="icon text-white-50"><i class="fa fa-expand"></i></span>
                <span class="text">Extrair</span>
              </button>
            </div>

            <div class="cp-hint">
              <i class="fas fa-info-circle"></i>
              Cole um link M3U e clique em <b>Extrair</b> para preencher DNS, usuário e senha automaticamente.
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- CARD 2: Criar Usuário -->
    <div class="cp-card">
      <div class="cp-head">
        <h6 class="cp-title"><i class="fas fa-user-plus"></i> Criar Usuário</h6>
      </div>
      <div class="cp-body">

        <form method="post">

          <div class="cp-row">
            <div class="form-group">
              <label class="control-label cp-label-strong" for="mac_address">Endereço MAC</label>
              <div class="input-group">
                <input class="form-control" id="mac_address" name="mac_address" placeholder="AA:BB:CC:DD:EE:FF" type="text" value="<?php echo strtoupper($index); ?>" required/>
              </div>
            </div>

            <div class="form-group">
              <label class="control-label cp-label-strong" for="title">Servidor</label>
              <div class="input-group">
                <input type="text" class="form-control" name="title" placeholder="Nome do servidor..." id="discription" value="<?php echo $randomPlaylistName; ?>" required/>
              </div>
            </div>

            <div class="form-group">
              <label class="control-label cp-label-strong" for="dns">DNS</label>
              <div class="input-group">
                <input type="text" class="form-control" name="dns" placeholder="https://seuservidor.com" id="server_url" required/>
              </div>
            </div>

            <div class="form-group">
              <label class="control-label cp-label-strong" for="Descricao">Descrição</label>
              <div class="input-group">
                <input type="text" class="form-control" name="Descricao" placeholder="Descrição do usuário..." id="Descricao" required/>
              </div>
            </div>

            <div class="form-group">
              <label class="control-label cp-label-strong" for="username">Nome de Usuário</label>
              <div class="input-group">
                <input type="text" class="form-control" name="username" placeholder="Usuário..." id="username" required/>
              </div>
            </div>

            <div class="form-group">
              <label class="control-label cp-label-strong" for="password">Senha</label>
              <div class="input-group">
                <input type="text" class="form-control" name="password" placeholder="Senha..." id="password" required/>
              </div>
            </div>
          </div>

          <div class="cp-divider"></div>

          <div class="form-group">
            <label class="control-label cp-label-strong" for="expire_date">Número de Anos (1 ano = 1 MAC)</label>
            <div class="input-group">
              <input type="number" placeholder="Número de Anos" class="form-control" name="expire_date" id="expire_date" value="1" min="1" max="999"/>
            </div>
          </div>

          <div class="form-group cp-actions mb-0">
            <button class="btn btn-success btn-icon-split" name="submit" type="submit">
              <span class="icon text-white-50"><i class="fas fa-check"></i></span>
              <span class="text">Submit</span>
            </button>

            <b id="gasto">A criação desse usuario irá consumir 1 MAC</b>
          </div>

        </form>

      </div>
    </div>

  </div><!-- /grid-wrap -->

</div><!-- /container -->

<br><br><br>

<script>
  var inputElement = document.getElementById("expire_date");
   function handleKeyDown(event) {
       var value = inputElement.value;
       if(value != '') {
       if(value <= 0) {
           value = 1;
       }
       
       if(value > 999) {
           value = 999;
       }
        inputElement.value = value;
       } else {
           value = '?';
       }
      
       document.getElementById("gasto").innerText = 'A criação desse usuario irá consumir ' + value + ' MAC';
   }

  inputElement.addEventListener("keydown", handleKeyDown);
  inputElement.addEventListener("keyup", handleKeyDown);
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>

</body>
<?php 
include '../includes/footer2.php';
?>
</html>
