<?php
ini_set('display_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))');

if (isset($_POST['submit'])) {
    $we   = strtotime($_POST['expire_date']);
    $ne   = date('Y-m-d', $we);
    $full = date('Y-m-d') . 'T' . date('h:m:s') . '.000000Z';
    $db->exec('INSERT INTO ibo(mac_address,username,password,expire_date,url,title,created_at) VALUES(\''
        . strtoupper(SQLite3::escapeString($_POST['mac_address'])) . '\',\''
        . SQLite3::escapeString($_POST['username']) . '\',\''
        . SQLite3::escapeString($_POST['password']) . '\',\''
        . $ne . '\',\''
        . SQLite3::escapeString($_POST['dns']) . '\',\''
        . SQLite3::escapeString($_POST['title']) . '\',\''
        . $full . '\')');
    $db->close();
    header('Location: users.php');
    exit;
}

$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'];
$randomPlaylistName = $playlistNames[array_rand($playlistNames)];

include 'includes/header.php';
?>

<div class="page-header">
  <h1><i class="fas fa-user-plus" style="color:var(--accent);font-size:18px"></i> Criar Cliente</h1>
  <p>Preencha os dados para ativar um novo usuário.</p>
</div>

<!-- M3U Extractor -->
<div class="u-card warning-left mb-4">
  <div class="u-card-header">
    <span class="u-card-title warning"><i class="fas fa-magic"></i> M3U Extractor <span style="color:var(--text-muted);font-weight:400;font-size:11px">(opcional)</span></span>
  </div>
  <div class="u-card-body">
    <div class="input-group">
      <input class="u-input" id="m3u_address" placeholder="Cole o link M3U aqui (ex: http://…/get.php?username=…&password=…)" type="text">
      <button class="u-btn u-btn-warning" onclick="extract(event)">
        <i class="fas fa-expand-arrows-alt"></i> Extrair
      </button>
    </div>
    <p class="form-hint">O extrator preenche automaticamente o servidor, usuário e senha.</p>
  </div>
</div>

<!-- Create Form -->
<div class="u-card accent-left glow">
  <div class="u-card-header">
    <span class="u-card-title"><i class="fas fa-id-card"></i> Dados do Cliente</span>
  </div>
  <div class="u-card-body">
    <form method="post">

      <div class="grid-2">
        <div class="form-group">
          <label class="form-label">MAC Address <span class="req">*</span></label>
          <input class="u-input" id="mac_address" name="mac_address"
                 placeholder="AA:BB:CC:DD:EE:FF" type="text" required>
        </div>
        <div class="form-group">
          <label class="form-label">Server Name <span class="req">*</span></label>
          <input class="u-input" name="title" id="discription"
                 placeholder="Nome do servidor"
                 value="<?php echo htmlspecialchars($randomPlaylistName); ?>" required>
        </div>
        <div class="form-group">
          <label class="form-label">DNS / Servidor <span class="req">*</span></label>
          <input class="u-input" name="dns" id="server_url" placeholder="http://servidor.com" required>
        </div>
        <div class="form-group">
          <label class="form-label">Username <span class="req">*</span></label>
          <input class="u-input" name="username" id="username" placeholder="Usuário" required>
        </div>
        <div class="form-group">
          <label class="form-label">Password <span class="req">*</span></label>
          <input class="u-input" name="password" id="password" placeholder="Senha" required>
        </div>
        <div class="form-group">
          <label class="form-label">Data de Expiração</label>
          <input class="u-input" name="expire_date" id="datetimepicker" placeholder="YYYY-MM-DD" type="text">
        </div>
      </div>

      <div class="flex gap-3 mt-2">
        <button class="u-btn u-btn-success u-btn-lg" name="submit" type="submit">
          <i class="fas fa-check"></i> Criar Cliente
        </button>
        <a href="users.php" class="u-btn u-btn-ghost u-btn-lg">
          <i class="fas fa-arrow-left"></i> Voltar
        </a>
      </div>

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

<script>
document.addEventListener("DOMContentLoaded", function () {
    var macInput = document.getElementById("mac_address");
    if (macInput) {
        macInput.addEventListener("input", function (e) {
            var v = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
            var f = "";
            for (var i = 0; i < v.length; i++) {
                f += v[i];
                if ((i + 1) % 2 === 0 && i < v.length - 1) f += ":";
            }
            e.target.value = f;
        });
    }
});
function extract(event) {
    event.preventDefault();
    var m3uLink = document.getElementById("m3u_address").value;
    document.getElementById("server_url").value = m3uLink.split("/get.php")[0];
    document.getElementById("username").value  = getParam("username", m3uLink);
    document.getElementById("password").value  = getParam("password", m3uLink);
}
function getParam(name, url) {
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results || !results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

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