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

include('includes/functions.php'); // conexão e $db

// --- Normalizar MAC ---
function normalise_mac(string $raw): string {
    $dec = base64_decode($raw, true);
    if ($dec !== false) $raw = $dec;
    $raw = strtolower(trim($raw));
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);
    $hex = preg_replace('/[^0-9a-f]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), static fn($p) => strlen($p) === 2);
    return implode(':', $pairs);
}

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

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

    if (isset($_POST['mac_address'])) {
        $_POST['mac_address'] = normalise_mac($_POST['mac_address']);
    }

    if (empty($_POST['device_key'])) {
        $chars = '1234567890';
        $deviceKey = '';
        for ($i = 0; $i < 8; $i++) {
            $deviceKey .= $chars[random_int(0, strlen($chars) - 1)];
        }
        $_POST['device_key'] = $deviceKey;
    }

    $existing = $db->select($table_name, "*", "mac_address = :mac AND dns_id = :dns", "", [
        ":mac" => $_POST['mac_address'],
        ":dns" => $_POST['dns_id']
    ]);

    if ($existing) {
        $db->update($table_name, $_POST, "mac_address = :mac AND dns_id = :dns", [
            ":mac" => $_POST['mac_address'],
            ":dns" => $_POST['dns_id']
        ]);
        $msg = "Usuário/MAC atualizado com sucesso!";
    } else {
        $db->insert($table_name, $_POST);
        $msg = "Usuário/MAC ativado com sucesso!";
    }

    $row = $db->select($table_name, "*", "mac_address = :mac AND dns_id = :dns", "", [
        ":mac" => $_POST['mac_address'],
        ":dns" => $_POST['dns_id']
    ]);
    $row = $row ? $row[0] : [];

    $response = [
        "status" => "ok",
        "message" => $msg,
        "data" => $row
    ];

    if (
        isset($_SERVER['HTTP_ACCEPT']) &&
        strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false
    ) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Ativar IPTV</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { background:#001a33; color:#fff; font-family:sans-serif; min-height:100vh;
               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 { 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; }

        label, input::placeholder, select, option {
    color: #fff;
}
        input, select {
    background-color: #003366;
    color: #fff;
    border: 1px solid #00aeef;
}
    </style>
</head>
<body>
<div class="card">
    <h2>Ativar Acesso IPTV</h2>

    <?php if ($response): ?>
        <div class="alert alert-success text-center">
            ✅ <?= htmlspecialchars($response['message'], ENT_QUOTES) ?>
        </div>
    <?php endif; ?>

    <form method="post">
        <!-- Campo M3U -->
        <label for="m3u">Lista M3U / URL Xtream</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>Extrai usuário, senha e tenta selecionar 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">Usuário</label>
        <input id="username" name="username" required>

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

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

        <!-- Link -->
        <label for="link">Link</label>
        <input id="link" name="link">

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

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

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

// Extrair dados da URL M3U
(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;
    try {
      const u = new URL(input.trim());
      let username = u.searchParams.get('username');
      let password = u.searchParams.get('password');
      return { hostPort: u.host, username, password, href: u.href };
    } catch(e){ return null; }
  }

  function selectDnsByHost(hostPort){
    if(!hostPort) 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('URL inválida'); 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>
