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

// Se veio com MAC via GET (de ativamac.php)
$prefilled_mac = isset($_GET['mac']) ? normalise_mac($_GET['mac']) : '';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Ativar IPTV</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="img/favicons/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background:#001a33; color:#fff; font-family:sans-serif; min-height:100vh;
               display:flex; justify-content:center; align-items:center; padding:2vmin; box-sizing:border-box; }
        .card { background:#002b55; padding:3vmin; border-radius:1.2vmin; box-shadow:0 0 1.5vmin rgba(0,0,0,.5); width:54vmin; max-width:54vmin; box-sizing:border-box; }
        .card h2 { margin-top:0; text-align:center; color:#FFD166; font-size:3vmin; }
        label { margin-top:1.5vmin; font-weight:bold; color:#fff; font-size:1.8vmin; }
        input, select { width:100%; padding:1vmin; border:none; border-radius:0.6vmin; margin-top:0.5vmin;
                        background-color:#003366; color:#fff; border:1px solid #00aeef; font-size:1.6vmin; }
        button { margin-top:2vmin; padding:1.2vmin 2.5vmin; border:none; border-radius:0.6vmin;
                 background:#00aeef; color:#fff; font-weight:bold; cursor:pointer; width:100%; font-size:1.8vmin; }
        button:hover { background:#007bbd; }
        small { opacity:.8; display:block; margin-top:0.4vmin; font-size:1.2vmin; }
        
        /* Responsivo para celulares */
        @media (max-width: 768px) {
            body { padding:0; }
            .card { width:100vw; max-width:100vw; height:100vh; max-height:100vh; padding:8vw 5vw; border-radius:0; box-shadow:none; display:flex; flex-direction:column; justify-content:center; }
            .card h2 { font-size:6vw; margin-bottom: 5vw; }
            label { margin-top:4vw; font-size:3.5vw; }
            input, select { padding:2.5vw; border-radius:1.5vw; margin-top:1.5vw; font-size:3vw; }
            button { margin-top:4vw; padding:3vw 5vw; border-radius:1.5vw; font-size:3.5vw; }
            small { margin-top:1vw; font-size:2.5vw; }
        }
    </style>
</head>
<body>
<div class="card">
    <h2>Ativar Acesso MAC</h2>

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

    <?php
// Mostrar infos se MAC já existir
if (!empty($prefilled_mac)) {
    $macData = $db->select(
        "playlist p JOIN dns d ON p.dns_id = d.id",
        "p.mac_address, p.username, p.password, d.title as dns",
        "LOWER(p.mac_address) = :mac",
        "",
        [":mac" => strtolower($prefilled_mac)]
    );

    if ($macData) {
        $info = $macData[0];
        ?>
        <div class="alert alert-info">
            <h5 class="text-center mb-3"><b>✅ ACESSO ATIVADO COM SUCESSO</b></h5>
            <p><i class="fa-solid fa-network-wired"></i> <b>MAC:</b> <?= strtoupper(htmlspecialchars($info['mac_address'])) ?></p>
            <p><i class="fa-solid fa-server"></i> <b>Servidor/DNS:</b> <?= htmlspecialchars($info['dns']) ?></p>
            <p><i class="fa-solid fa-user"></i> <b>Usuário:</b> <?= htmlspecialchars($info['username']) ?></p>
            <p><i class="fa-solid fa-lock"></i> <b>Senha:</b> ******</p>
            <div class="d-flex gap-2 mt-3">
                <button class="btn btn-sm btn-light" onclick="copyInfo()">
                    <i class="fa-solid fa-copy"></i> Copiar
                </button>
                <a class="btn btn-sm btn-success" id="sendZap" target="_blank">
                    <i class="fa-brands fa-whatsapp"></i> Enviar
                </a>
                <a class="btn btn-sm btn-primary" href="ativar.php">
                    <i class="fa-solid fa-plus"></i> Adicionar Novo
                </a>
            </div>
        </div>

        <script>
        document.addEventListener('DOMContentLoaded', function () {
          const mac  = <?= json_encode(strtoupper($info['mac_address'] ?? '')) ?>;
          const dns  = <?= json_encode($info['dns'] ?? '') ?>;
          const user = <?= json_encode($info['username'] ?? '') ?>;

          const msg =
  `⚡ *ACESSO ATIVADO COM SUCESSO* ⚡\n\n` +
  `💻 MAC: ${mac.toUpperCase()}\n` +
  `🌐 Servidor: ${dns}\n` +
  `👤 Usuário: ${user}\n\n` +
  `⚠️ *Para renovar informe estes dados*`;

          const zap = document.getElementById("sendZap");
          if (zap) {
            zap.href = "https://wa.me/?text=" + encodeURIComponent(msg);
          }

          // usa o mesmo texto no botão Copiar
          window.copyInfo = function () {
            navigator.clipboard.writeText(msg).then(() => alert("Informações copiadas!"));
          };
        });
            </script>
            <?php
        }
    }
    ?>

    <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" value="<?=htmlspecialchars($prefilled_mac)?>" 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>