<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include('includes/functions.php'); // conexão já existente

// --- Função para normalizar MAC ---
function normalise_mac(string $raw): string {
    $hex = preg_replace('/[^0-9a-f]/i', '', $raw);
    $pairs = array_filter(str_split($hex, 2), fn($p) => strlen($p) === 2);
    return strtoupper(implode(':', $pairs));
}

$table_name = "playlist";
$dnss = $db->select('dns', '*', '', '');

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

    // Normaliza MAC
    if (!empty($_POST['mac_address'])) {
        $_POST['mac_address'] = normalise_mac($_POST['mac_address']);
    }

    // Gera device_key se não informado
    if (empty($_POST['device_key'])) {
        $_POST['device_key'] = substr(str_shuffle("0123456789"), 0, 8);
    }

    $db->insert($table_name, $_POST);

    echo "<script>alert('Usuário/MAC ativado com sucesso!'); window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "';</script>";
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Ativar Dispositivo</title>
    <style>
        body { background:#001a33; color:#fff; font-family:sans-serif; min-height:100vh; margin:0; display:flex; justify-content:center; align-items:flex-start; padding:40px; }
        .card { background:#002b55; padding:30px; border-radius:12px; box-shadow:0 0 15px rgba(0,0,0,.5); width:500px; }
        .card h2 { margin-top:0; text-align:center; color:#FFD166; }
        label { display:block; margin-top:15px; font-weight:bold; }
        input, select { width:100%; padding:10px; border:none; border-radius:6px; margin-top:5px; }
        button { margin-top:20px; padding:12px 25px; border:none; border-radius:6px; background:#00aeef; color:#fff; font-weight:bold; cursor:pointer; width:100%; }
        button:hover { background:#007bbd; }
        small { opacity:.8; display:block; margin-top:4px; }
    </style>
</head>
<body>
<div class="card">
    <h2>Ativar Dispositivo</h2>

    <form method="post">
        <!-- Campo M3U -->
        <label for="m3u">Lista M3U / URL Xtream (opcional)</label>
        <div style="display:flex; gap:8px;">
            <input id="m3u" type="text" placeholder="Cole a URL M3U ou Xtream" style="flex:1;">
            <button id="btnExtract" type="button" style="width:auto;background:#28a745;">Extrair</button>
        </div>
        <small>Ao clicar em Extrair, preenche Usuário, Senha e tenta selecionar o DNS automaticamente.</small>

        <!-- DNS -->
        <label for="dns_id">DNS</label>
        <select name="dns_id" required>
            <option value="" disabled selected>Selecione uma opção</option>
            <?php foreach($dnss as $dns) { ?>
                <option value="<?=$dns['id']?>" data-url="<?=htmlspecialchars($dns['url'], ENT_QUOTES)?>"><?=$dns['title']?></option>
            <?php } ?>
        </select>

        <!-- MAC -->
        <label for="mac">Endereço MAC</label>
        <input id="mac" name="mac_address" placeholder="Ex: A1B2C3D4E5F6" required>

        <!-- Username -->
        <label for="username">Nome de Usuário</label>
        <input id="username" name="username" placeholder="Usuário" required>

        <!-- Password -->
        <label for="password">Senha</label>
        <input id="password" name="password" placeholder="Senha" required>

        <!-- PIN -->
        <label for="pin">PIN Parental</label>
        <input id="pin" name="pin" value="0000" required>

        <!-- Link -->
        <label for="link">Link</label>
        <input id="link" name="link" placeholder="Link (opcional)">

        <input type="hidden" name="device_key" value="">

        <button type="submit" name="submit">Salvar / Ativar</button>
    </form>
</div>

<script>
// Formata MAC automaticamente
document.getElementById("mac").addEventListener('keyup', function() {
    this.value = (this.value.toUpperCase().replace(/[^0-9A-F]/g, '').match(/.{1,2}/g) || []).join(":");
});

// Extrair dados de URL M3U / Xtream
(function(){
  const $m3u = document.getElementById('m3u');
  const $btn = document.getElementById('btnExtract');
  if(!$m3u || !$btn) return;

  const $user = document.getElementById('username');
  const $pass = document.getElementById('password');
  const $link = document.getElementById('link');
  const $dnsSelect = document.querySelector('select[name="dns_id"]');

  function parseM3U(input){
    if(!input) return null;
    const str = input.trim();
    try {
      const u = new URL(str);
      let username = u.searchParams.get('username') || u.searchParams.get('user');
      let password = u.searchParams.get('password') || u.searchParams.get('pass');
      return { hostPort: u.host, username, password, href: u.href };
    } catch(e){
      return null;
    }
  }

  function selectDnsByHost(hostPort){
    if(!hostPort || !$dnsSelect) return;
    const hostOnly = hostPort.split(':')[0].toLowerCase();
    for(const option of $dnsSelect.options){
        const dnsUrl = option.dataset.url;
        if(!dnsUrl) continue;
        try {
            const dnsHost = new URL(dnsUrl).hostname.toLowerCase();
            if(dnsHost === hostOnly) {
                $dnsSelect.value = option.value;
                break;
            }
        } catch(e) {}
    }
  }

  $btn.addEventListener('click', function(){
    const out = parseM3U($m3u.value);
    if(!out){ alert('Não foi possível ler a URL.'); return; }
    if(out.username) $user.value = decodeURIComponent(out.username);
    if(out.password) $pass.value = decodeURIComponent(out.password);
    if(out.href)     $link.value = out.href;
    selectDnsByHost(out.hostPort);
  });
})();
</script>
</body>
</html>



