<?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

}

if(isset($_GET['update'])) {
    $user_id = $_GET['update'];
    $res1 = $db->query("SELECT * FROM ibo WHERE id = '$user_id'");
    while ($row1 = $res1->fetchArray()) {

        $user_id = $row1['id'];
        $username = $row1['username'];
        $password = $row1['password'];

        $mac_address_old = $row1['mac_address'];
        $dns = $row1['url'];
        $extra = $row1['extra'];
        $title = $row1['title'];

        // (mantém compatibilidade com seu form, mesmo que não venha do SELECT original em algumas bases)
        $expire_date = $row1['expire_date'] ?? '';
    }
} else {
    echo "<script>alert('Selecione o usuario a ser editado!');</script>";
    header('Location: index.php');
}

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

if (isset($_POST['submit'])) {

     $usuario =  $_POST['username'];
     	$mac_adress = strtoupper($_POST['mac_address']);
             $result = $db1->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_adress' AND mac_address <> '$mac_address_old'");
            $row = $result->fetchArray(SQLITE3_ASSOC);
            $count = $row['count'];

            if($count || $usuario == "ADM") {
              echo "<script>alert('Já existe um usuario registrado com esse usuario que você esta tentando, por favor escolha outro!');window.location.href='index.php';</script>";
            } else {


        	$start = date('Y-m-d');
        	$end = date('h:m:s');
        	$full = $start . 'T' . $end . '.000000Z';

        	$username = $_POST['username'];
        	$password = $_POST['password'];
        	$dns = $_POST['url'];
        	$title = $_POST['title'];
        	$id = $_POST['id'];
        	$Descricao = $_POST['Descricao'];

        	$db1->exec("UPDATE ibo SET mac_address = '$mac_adress', username = '$username', password = '$password', url = '$dns', title = '$title', extra = '$Descricao' WHERE id = '$id'");

        	$db1->close();
            echo "<script>window.location.href='index.php';</script>";
            }

}

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

    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 PADRÃO (cyberpunk estável, sem blur em cards)
   Apenas visual — não mexe em funções
========================================================= */
:root{
  --cp-stroke: rgba(255,255,255,.14);
  --cp-stroke2: rgba(255,255,255,.10);
  --cp-text: rgba(255,255,255,.92);
  --cp-muted: rgba(255,255,255,.65);
  --cp-shadow: 0 18px 60px rgba(0,0,0,.55);

  --neon-cyan: #00f2ff;
  --neon-purple: #bc13fe;
  --danger: #ff4b2b;
}

#content-wrapper,
#content{
  background: transparent !important;
}

.page-title{
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .08em;
  text-transform: uppercase;
  color: rgba(0,242,255,.92);
  text-shadow: 0 0 14px rgba(0,242,255,.20);
}

.page-sub{
  color: rgba(255,255,255,.70);
}

.cy-card{
  background: linear-gradient(180deg, rgba(255,255,255,.10), rgba(255,255,255,.04)) !important;
  border: 1px solid var(--cp-stroke) !important;
  border-radius: 18px !important;
  box-shadow: var(--cp-shadow) !important;
  overflow: hidden;
}

.cy-card .card-header{
  background: linear-gradient(90deg, rgba(0,242,255,.10), rgba(188,19,254,.06), rgba(255,43,214,.05)) !important;
  border-bottom: 1px solid rgba(255,255,255,.10) !important;
}

.cy-card .card-header h6{
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-transform: uppercase;
  color: rgba(0,242,255,.92) !important;
  margin: 0;
}

.cy-form-label{
  font-family: 'Orbitron', sans-serif;
  letter-spacing: .06em;
  text-transform: uppercase;
  font-size: 12px;
  color: rgba(255,255,255,.80);
}

.form-control{
  background: rgba(0,0,0,.28) !important;
  border: 1px solid rgba(255,255,255,.14) !important;
  color: rgba(255,255,255,.92) !important;
  border-radius: 14px !important;
  box-shadow: none !important;
}

.form-control:focus{
  border-color: rgba(0,242,255,.40) !important;
  box-shadow: 0 0 0 .2rem rgba(0,242,255,.08) !important;
}

.form-control::placeholder{
  color: rgba(255,255,255,.45) !important;
}

.btn{
  border-radius: 999px !important;
  font-weight: 900 !important;
  letter-spacing: .06em;
  text-transform: uppercase;
  font-family: 'Orbitron', sans-serif;
}

.btn-save{
  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;
  padding: 10px 18px !important;
}

.btn-save:hover{
  background: rgba(0,242,255,.16) !important;
  box-shadow: 0 0 34px rgba(0,242,255,.18) !important;
  transform: translateY(-1px);
}

.btn-back{
  background: rgba(255,255,255,.06) !important;
  border: 1px solid rgba(255,255,255,.14) !important;
  color: rgba(255,255,255,.85) !important;
  padding: 10px 16px !important;
}

.btn-back:hover{
  background: rgba(188,19,254,.10) !important;
  border-color: rgba(188,19,254,.35) !important;
}

.help-chip{
  display:inline-flex;
  align-items:center;
  gap:10px;
  padding: 10px 14px;
  border-radius: 14px;
  border: 1px solid rgba(255,255,255,.10);
  background: rgba(0,0,0,.22);
  color: rgba(255,255,255,.75);
  font-size: 12px;
}
.help-chip i{ color: rgba(188,19,254,.85); }

.hr-soft{
  border-top: 1px solid rgba(255,255,255,.10);
  margin: 18px 0;
}
</style>

<div class="container-fluid">

  <div class="d-flex align-items-center justify-content-between flex-wrap mb-3">
    <div>
      <h1 class="h3 mb-1 page-title"><i class="fas fa-user-edit mr-2"></i>Atualizar Usuário</h1>
      <div class="page-sub">Edite os dados do usuário mantendo o padrão do painel.</div>
    </div>

    <div class="d-flex align-items-center mt-2">
      <a href="index.php" class="btn btn-back mr-2">
        <i class="fas fa-arrow-left mr-2"></i>Voltar
      </a>
      <div class="help-chip">
        <i class="fas fa-info-circle"></i>
        Dica: o MAC é formatado automaticamente (AA:BB:CC...).
      </div>
    </div>
  </div>

  <div class="card cy-card mb-4">
    <div class="card-header py-3">
      <h6><i class="fas fa-user mr-2"></i>Editar Usuário</h6>
    </div>

    <div class="card-body">
      <form method="post">
        <!-- id hidden (mantém função) -->
        <input class="form-control" name="id" value="<?php echo $user_id; ?>" type="hidden" readonly>

        <div class="row">
          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="mac_address"><strong>Endereço MAC</strong></label>
              <input class="form-control" id="mac_address" name="mac_address" value="<?php echo $mac_address_old; ?>" type="text" required/>
            </div>
          </div>

          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="title"><strong>Servidor</strong></label>
              <input type="text" class="form-control" name="title" value="<?php echo $title; ?>" id="title" required/>
            </div>
          </div>

          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="username"><strong>Usuário</strong></label>
              <input type="text" class="form-control" name="username" value="<?php echo $username; ?>" id="username" required/>
            </div>
          </div>

          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="password"><strong>Senha</strong></label>
              <input type="text" class="form-control" name="password" value="<?php echo $password; ?>" id="password" required/>
            </div>
          </div>

          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="datepicker"><strong>Validade</strong></label>
              <input type="text" class="form-control" name="expire_date" value="<?php echo $expire_date; ?>" id="datepicker" />
            </div>
          </div>

          <div class="col-lg-6">
            <div class="form-group">
              <label class="cy-form-label" for="url"><strong>DNS</strong></label>
              <input type="text" class="form-control" name="url" value="<?php echo $dns; ?>" id="url" required/>
            </div>
          </div>

          <div class="col-12">
            <div class="form-group">
              <label class="cy-form-label" for="Descricao"><strong>Descrição (Extra)</strong></label>
              <input type="text" class="form-control" name="Descricao" value="<?php echo $extra; ?>" id="Descricao" required/>
            </div>
          </div>
        </div>

        <div class="hr-soft"></div>

        <div class="d-flex align-items-center justify-content-between flex-wrap">
          <a href="index.php" class="btn btn-back">
            <i class="fas fa-arrow-left mr-2"></i>Cancelar
          </a>

          <button class="btn btn-save" name="submit" type="submit">
            <i class="fas fa-check mr-2"></i>Salvar Alterações
          </button>
        </div>

      </form>
    </div>
  </div>

  <br><br><br>
</div>

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

<?php 
include '../includes/footer3.php';
?>

</html>
