<?php
// Silencia avisos para manter o visual limpo
ini_set('display_errors', 0);
error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);

$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);
    $start = date('Y-m-d');
    $end = date('H:i:s');
    $full = $start . 'T' . $end . '.000000Z';
    
    // Limpeza do MAC para o banco
    $mac_limpo = strtoupper(preg_replace('/[^a-fA-F0-9]/', '', $_POST['mac_address']));
    
    // Captura dos dados extraídos
    $username = $_POST['username'];
    $password = $_POST['password'];
    $dns      = $_POST['dns'];
    $title    = $_POST['title'];

    // Se o usuário colou a URL mas não clicou em extrair, tentamos reconstruir aqui por segurança
    if(empty($username) && !empty($_POST['m3u_raw'])) {
        parse_str(parse_url($_POST['m3u_raw'], PHP_URL_QUERY), $query);
        $username = $query['username'] ?? '';
        $password = $query['password'] ?? '';
        $dns = explode('/get.php', $_POST['m3u_raw'])[0];
    }

    $stmt = $db->prepare('INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at) VALUES(:mac, :user, :pass, :expire, :url, :title, :created)');
    $stmt->bindValue(':mac', $mac_limpo, SQLITE3_TEXT);
    $stmt->bindValue(':user', $username, SQLITE3_TEXT);
    $stmt->bindValue(':pass', $password, SQLITE3_TEXT);
    $stmt->bindValue(':expire', $ne, SQLITE3_TEXT);
    $stmt->bindValue(':url', $dns, SQLITE3_TEXT);
    $stmt->bindValue(':title', $title, SQLITE3_TEXT);
    $stmt->bindValue(':created', $full, SQLITE3_TEXT);
    
    $stmt->execute();
    $db->close();
    header('Location: users.php');
    exit();
}

$playlistNames = ['Cliente FLUX', 'FLUX PLAYER', 'Servidor FLUX', 'FLUX PRO', 'FLUX VIP'];
$randomPlaylistName = $playlistNames[array_rand($playlistNames)];

include 'includes/header.php';
?>

<style>
    /* FUNDO E ESTRUTURA - MANTIDO INTEGRALMENTE */
    #content-wrapper, #content, .container-fluid, main { background-color: #06070a !important; }

    .flux-input {
        background: rgba(255,255,255,0.03) !important;
        border: 1px solid rgba(139, 92, 246, 0.1) !important;
        border-radius: 12px !important;
        color: white !important;
        padding: 14px !important;
        transition: all 0.3s;
        font-size: 14px;
    }
    .flux-input:focus {
        border-color: #8b5cf6 !important;
        background: rgba(139, 92, 246, 0.05) !important;
        outline: none;
    }
    
    .label-thai {
        color: #8b5cf6;
        font-size: 10px;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: 1.5px;
        margin-bottom: 8px;
        display: block;
        opacity: 0.8;
    }

    @media (max-width: 768px) {
        .card-main { padding: 20px !important; border-radius: 25px !important; }
        .title-section h1 { font-size: 22px !important; }
    }
</style>

<main class="py-4 md:py-8 px-2">
    <div class="max-w-4xl mx-auto">
        
        <div class="mb-8 flex flex-col md:flex-row items-center justify-between gap-4 text-center md:text-left title-section">
            <div>
                <h1 class="text-3xl font-black text-white tracking-tighter italic uppercase">Cadastrar Acesso</h1>
                <p class="text-[9px] text-violet-500 font-bold uppercase tracking-[0.4em]">VU FLUX • NOVO CLIENTE</p>
            </div>
            <a href="users.php" class="px-5 py-2 bg-white/5 text-gray-400 text-[10px] font-black rounded-full border border-white/5 uppercase">
                <i class="fas fa-arrow-left mr-1"></i> Voltar
            </a>
        </div>

        <div class="bg-[#0f111a] card-main rounded-[2.5rem] border border-white/5 p-8 shadow-2xl relative overflow-hidden">
            <div class="absolute -top-24 -left-24 w-64 h-64 bg-violet-600/5 blur-[100px]"></div>
            
            <form method="post" class="space-y-6 relative z-10">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label class="label-thai">Endereço MAC</label>
                        <input class="w-full flux-input font-mono text-center tracking-[4px] uppercase" id="mac_address" name="mac_address" placeholder="AABBCC112233" type="text" maxlength="12" required/>
                    </div>

                    <div>
                        <label class="label-thai">Nome do Cliente</label>
                        <input type="text" class="w-full flux-input" name="title" value="<?php echo $randomPlaylistName; ?>" required/>
                    </div>
                </div>

                <div class="bg-emerald-500/5 p-5 md:p-6 rounded-[2rem] border border-emerald-500/10">
                    <label class="label-thai" style="color: #10b981;">Importar via Link M3U</label>
                    <div class="flex flex-col gap-3">
                        <input class="w-full flux-input text-[11px] opacity-70" id="m3u_address" name="m3u_raw" placeholder="Cole o link M3U aqui..." type="text"/>
                        <button type="button" class="w-full py-3 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-[10px] font-black transition-all flex items-center justify-center gap-2" onclick="extractM3U(event)">
                            <i class="fas fa-magic"></i> EXTRAIR DADOS AUTOMATICAMENTE
                        </button>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div>
                        <label class="label-thai">DNS (Server)</label>
                        <input type="text" class="w-full flux-input text-xs" name="dns" id="server_url" readonly required/>
                    </div>
                    <div>
                        <label class="label-thai">Usuário</label>
                        <input type="text" class="w-full flux-input text-xs" name="username" id="username" readonly required/>
                    </div>
                    <div>
                        <label class="label-thai">Senha</label>
                        <input type="text" class="w-full flux-input text-xs" name="password" id="password" readonly required/>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5 items-end">
                    <div>
                        <label class="label-thai">Vencimento</label>
                        <input type="text" value="2050-01-01" class="w-full flux-input text-center font-bold text-violet-400 bg-violet-400/5" name="expire_date" id="datetimepicker"/>
                    </div>
                    
                    <div class="pt-4 md:pt-0">
                        <button class="w-full py-4 bg-violet-600 hover:bg-violet-700 text-white rounded-2xl text-[11px] font-black shadow-xl shadow-violet-900/20 flex items-center justify-center gap-3 transition-all uppercase tracking-widest" name="submit" type="submit">
                            <i class="fas fa-save text-lg"></i> Cadastrar no Flux
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</main>

<script>
document.getElementById("mac_address").addEventListener("input", function(e) {
    let value = e.target.value.toUpperCase().replace(/[^A-F0-9]/g, "");
    e.target.value = value.substring(0, 12);
});

function extractM3U(event) {
    event.preventDefault();
    var m3uLink = document.getElementById("m3u_address").value.trim();
    
    if(!m3uLink) {
        alert("Por favor, cole um link M3U.");
        return;
    }

    try {
        // Detecta se é link XC (get.php) ou M3U padrão com parâmetros
        if(m3uLink.includes("get.php")) {
            document.getElementById("server_url").value = m3uLink.split("/get.php")[0];
            document.getElementById("username").value = getParam("username", m3uLink);
            document.getElementById("password").value = getParam("password", m3uLink);
        } else {
            // Tentativa genérica para outros formatos de link que contenham user/pass
            document.getElementById("username").value = getParam("user", m3uLink) || getParam("username", m3uLink);
            document.getElementById("password").value = getParam("pass", m3uLink) || getParam("password", m3uLink);
            
            // Tenta isolar o DNS
            var url = new URL(m3uLink);
            document.getElementById("server_url").value = url.protocol + "//" + url.host;
        }
    } catch (e) {
        alert("Erro ao processar o link. Certifique-se de que é uma URL válida.");
    }
}

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