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

if (file_exists('config.php')) {
    include 'config.php';
} else {
    die("Erro: Configuração não encontrada.");
}

$message = "";

// Verifica se há um status na URL para exibir o feedback após o redirecionamento
if (isset($_GET['status'])) {
    $message = $_GET['status'];
}

if (isset($_POST['submit'])) {
    try {
        $db = new SQLite3('../a/.eggziedb.db');
        $mac = preg_replace('/[^0-9]/', '', $_POST['mac_address']);
        $username = $_POST['username'];
        $password = $_POST['password'];
        $dns      = $_POST['dns'];
        $title    = $_POST['title']; 
        $expire   = '2050-01-01'; 

        if (!empty($mac) && !empty($username)) {
            // 1. Deleta registros anteriores para o mesmo MAC
            $db->exec("DELETE FROM ibo WHERE mac_address = '$mac'");

            // 2. Insere a nova configuração
            $insertQuery = "INSERT INTO ibo (mac_address, username, password, expire_date, url, title) 
                            VALUES ('$mac', '$username', '$password', '$expire', '$dns', '$title')";
            
            if ($db->exec($insertQuery)) {
                $db->close();
                // REDIRECIONAMENTO para evitar reenvio de formulário ao atualizar (F5)
                header("Location: index.php?status=success");
                exit();
            }
        }
        $db->close();
    } catch (Exception $e) { 
        header("Location: index.php?status=error");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FLUX PLAYER | VINCULAR</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        body { background-color: #06070a; background-image: radial-gradient(circle at top right, rgba(139, 92, 246, 0.05), transparent); }
        
        .flux-input { 
            background: rgba(255,255,255,0.03) !important; 
            border: 1px solid rgba(139, 92, 246, 0.2) !important; 
            border-radius: 15px !important; 
            color: white !important; 
            transition: all 0.3s; 
        }

        /* CORREÇÃO DEFINITIVA PARA O SELECT BRANCO NO CHROME/PC */
        select.flux-input {
            background-color: #0f111a !important;
            color: white !important;
        }

        /* Estiliza as opções internas do select */
        select option {
            background: #0f111a !important;
            color: white !important;
            padding: 12px !important;
        }

        .flux-input:focus { border-color: #8b5cf6 !important; box-shadow: 0 0 20px rgba(139, 92, 246, 0.15) !important; }
        .label-thai { color: #8b5cf6; font-size: 10px; text-transform: uppercase; font-weight: 900; letter-spacing: 2px; margin-bottom: 8px; display: block; }
        .btn-disabled { opacity: 0.3; cursor: not-allowed !important; filter: grayscale(1); }
        .mac-invalid { border-color: #ef4444 !important; color: #ef4444 !important; }
        .mac-valid { border-color: #10b981 !important; }
    </style>
</head>
<body class="text-white min-h-screen flex items-center justify-center p-4">

    <div class="max-w-md w-full animate__animated animate__fadeIn">
        <div class="text-center mb-8">
            <img src="https://5.zyx.lat/vu-02/rtx/logo/697b775635f23.png" class="h-16 mx-auto mb-4">
            <h1 class="text-2xl font-black italic uppercase text-white">Vincular Acesso</h1>
        </div>

        <div class="bg-[#0f111a] rounded-[2.5rem] border border-white/5 p-8 shadow-3xl">
            <form method="POST" id="mainForm" class="space-y-5">
                <div>
                    <label class="label-thai">ID DO DISPOSITIVO (MAC)</label>
                    <input type="text" name="mac_address" id="mac_address" required
                        class="w-full flux-input px-5 py-4 outline-none font-mono text-center text-xl tracking-[3px]"
                        placeholder="DIGITE SEU ID" autocomplete="off">
                    <p id="mac_feedback" class="text-[9px] mt-2 font-bold uppercase text-center hidden"></p>
                </div>

                <div class="space-y-5 opacity-40 transition-opacity duration-500" id="form_fields">
                    <div>
                        <label class="label-thai">Selecione o Servidor</label>
                        <select name="dns" id="dns_select" required onchange="updateTitle(this)"
                            class="w-full flux-input px-5 py-4 outline-none cursor-pointer">
                            <option value="" disabled selected>SELECIONE...</option>
                            <?php if(isset($servidores)): foreach($servidores as $nome => $url): ?>
                                <option value="<?php echo $url; ?>"><?php echo $nome; ?></option>
                            <?php endforeach; endif; ?>
                        </select>
                    </div>

                    <input type="hidden" name="title" id="list_title" value="">

                    <div class="grid grid-cols-2 gap-4">
                        <input type="text" name="username" placeholder="USUÁRIO" required class="flux-input px-4 py-3 text-center text-sm outline-none">
                        <input type="text" name="password" placeholder="SENHA" required class="flux-input px-4 py-3 text-center text-sm outline-none">
                    </div>

                    <button type="submit" name="submit" id="btn_submit" disabled
                        class="w-full bg-violet-600 btn-disabled text-white font-black py-5 rounded-2xl shadow-lg transition-all uppercase text-xs flex items-center justify-center gap-3">
                        <i class="fas fa-bolt"></i> ATIVAR AGORA
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Lógica de validação do MAC
        const macInput = document.getElementById('mac_address');
        const feedback = document.getElementById('mac_feedback');
        const formFields = document.getElementById('form_fields');
        const btnSubmit = document.getElementById('btn_submit');

        macInput.addEventListener('input', async function() {
            let val = this.value.replace(/[^0-9]/g, '');
            this.value = val;
            if (val.length >= 1) { 
                const response = await fetch(`check_mac.php?mac=${val}`);
                const data = await response.json();
                if (data.exists) {
                    this.classList.replace('mac-invalid', 'mac-valid') || this.classList.add('mac-valid');
                    feedback.innerHTML = '<i class="fas fa-check"></i> ID IDENTIFICADO';
                    feedback.className = "text-[9px] mt-2 font-bold uppercase text-center text-emerald-500 block";
                    formFields.style.opacity = "1";
                    btnSubmit.disabled = false;
                    btnSubmit.classList.remove('btn-disabled');
                } else {
                    this.classList.add('mac-invalid');
                    feedback.innerHTML = '<i class="fas fa-times"></i> ID NÃO ENCONTRADO';
                    feedback.className = "text-[9px] mt-2 font-bold uppercase text-center text-red-500 block";
                    formFields.style.opacity = "0.4";
                    btnSubmit.disabled = true;
                    btnSubmit.classList.add('btn-disabled');
                }
            }
        });

        function updateTitle(select) {
            document.getElementById('list_title').value = select.options[select.selectedIndex].text;
        }

        // Exibe o alerta e limpa a URL para evitar reenvio no F5
        <?php if($message == "success"): ?>
        Swal.fire({
            title: 'SUCESSO!',
            text: 'As listas antigas foram removidas e a nova foi ativada.',
            icon: 'success',
            background: '#0f111a',
            color: '#fff',
            confirmButtonColor: '#8b5cf6'
        }).then(() => { window.history.replaceState({}, document.title, "index.php"); });
        <?php endif; ?>
    </script>
</body>
</html>
