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

// Busca os dados atuais do usuário usando Prepared Statement por segurança
$stmt_get = $db->prepare('SELECT * FROM ibo WHERE id = :id');
$stmt_get->bindValue(':id', $_GET['update'], SQLITE3_INTEGER);
$res = $stmt_get->execute();
$row = $res->fetchArray(SQLITE3_ASSOC);

if (!$row) {
    header('Location: users.php');
    exit();
}

$id = $row['id'];
$mac_address = $row['mac_address'];
$expire_date = $row['expire_date'];
$username = $row['username'];
$password = $row['password'];
$title = $row['title'];
$url = $row['url'];

// Processa a atualização
if (isset($_POST['submit'])) {
    $expire_date_post = strtotime($_POST['expire_date']);
    $expire_date_post = date('Y-m-d', $expire_date_post);
    $created_at = date('Y-m-d H:i:s');
    
    // Limpa o MAC para garantir que salve sem pontuação
    $mac_limpo = strtoupper(preg_replace('/[^a-fA-F0-9]/', '', $_POST['mac_address']));

    // Lógica de segurança: se houver link M3U mas campos vazios, tenta extrair no PHP
    $dns_final = $_POST['url'];
    $user_final = $_POST['username'];
    $pass_final = $_POST['password'];

    if(empty($user_final) && !empty($_POST['m3u_raw'])) {
        parse_str(parse_url($_POST['m3u_raw'], PHP_URL_QUERY), $query);
        $user_final = $query['username'] ?? '';
        $pass_final = $query['password'] ?? '';
        $dns_final = explode('/get.php', $_POST['m3u_raw'])[0];
    }

    $stmt = $db->prepare('UPDATE ibo SET 
        mac_address = :mac,
        expire_date = :expire,
        username = :user,
        password = :pass,
        title = :title,
        url = :url,
        created_at = :created
        WHERE id = :id');

    $stmt->bindValue(':mac', $mac_limpo, SQLITE3_TEXT);
    $stmt->bindValue(':expire', $expire_date_post, SQLITE3_TEXT);
    $stmt->bindValue(':user', $user_final, SQLITE3_TEXT);
    $stmt->bindValue(':pass', $pass_final, SQLITE3_TEXT);
    $stmt->bindValue(':title', $_POST['title'], SQLITE3_TEXT);
    $stmt->bindValue(':url', $dns_final, SQLITE3_TEXT);
    $stmt->bindValue(':created', $created_at, SQLITE3_TEXT);
    $stmt->bindValue(':id', $_POST['id'], SQLITE3_INTEGER);

    $stmt->execute();
    $db->close();
    header('Location: users.php');
    exit();
}

include 'includes/header.php';
?>

<style>
    /* FUNDO ESTRUTURAL - 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) {
        .container-fluid { padding: 0 15px !important; }
        .card-main { padding: 20px !important; border-radius: 25px !important; }
        .title-section h1 { font-size: 24px !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">Editar Acesso</h1>
                <p class="text-[9px] text-violet-500 font-bold uppercase tracking-[0.4em]">VU FLUX • ATUALIZAR DADOS</p>
            </div>
            <a href="users.php" class="px-5 py-2 bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white text-[10px] font-black rounded-full transition-all border border-white/5 uppercase">
                <i class="fas fa-arrow-left mr-2"></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 -right-24 w-64 h-64 bg-violet-600/5 blur-[100px]"></div>
            
            <form method="post" class="space-y-6 relative z-10">
                <input name="id" value="<?php echo $id; ?>" type="hidden">
                
                <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" value="<?php echo $mac_address; ?>" 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 $title; ?>" required placeholder="Ex: João Silva"/>
                    </div>
                </div>

                <div class="bg-violet-600/5 p-5 md:p-6 rounded-[2rem] border border-violet-500/10">
                    <label class="label-thai">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 completo aqui..." type="text"/>
                        <button type="button" class="w-full py-3 bg-violet-600 hover:bg-violet-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="url" id="url" value="<?php echo $url; ?>" required/>
                    </div>
                    <div>
                        <label class="label-thai">Usuário</label>
                        <input type="text" class="w-full flux-input text-xs" name="username" id="username" value="<?php echo $username; ?>" required/>
                    </div>
                    <div>
                        <label class="label-thai">Senha</label>
                        <input type="text" class="w-full flux-input text-xs" name="password" id="password" value="<?php echo $password; ?>" required/>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-5 items-end">
                    <div>
                        <label class="label-thai">Data de Vencimento</label>
                        <div class="relative">
                            <input type="text" class="w-full flux-input text-center font-bold text-violet-400 bg-violet-400/5" name="expire_date" id="datetimepicker" value="<?php echo $expire_date; ?>" />
                        </div>
                    </div>
                    
                    <div class="pt-4 md:pt-0">
                        <button class="w-full py-4 bg-emerald-500 hover:bg-emerald-600 text-white rounded-2xl text-[11px] font-black shadow-xl shadow-emerald-500/20 flex items-center justify-center gap-3 transition-all uppercase tracking-widest" name="submit" type="submit">
                            <i class="fas fa-check-circle text-lg"></i> Salvar Alterações
                        </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 {
        if(m3uLink.includes("get.php")) {
            document.getElementById("url").value = m3uLink.split("/get.php")[0];
            document.getElementById("username").value = getParam("username", m3uLink);
            document.getElementById("password").value = getParam("password", m3uLink);
        } else {
            document.getElementById("username").value = getParam("user", m3uLink) || getParam("username", m3uLink);
            document.getElementById("password").value = getParam("pass", m3uLink) || getParam("password", m3uLink);
            var urlObj = new URL(m3uLink);
            document.getElementById("url").value = urlObj.protocol + "//" + urlObj.host;
        }
    } catch (e) {
        alert("Erro ao processar o link. Verifique se a URL está completa.");
    }
}

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