<?php
ini_set('display_errors', 0);
require_once "includes/header.php"; 

define('SECURITY_KEY', 'FLUX_SECRET_777_#@!'); 

function encryptData($data) {
    if(empty($data)) return '';
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', SECURITY_KEY, 0, $iv);
    return base64_encode($encrypted . '::' . $iv);
}

function decryptData($data) {
    if (!$data) return '';
    $parts = explode('::', base64_decode($data), 2);
    if(count($parts) < 2) return '';
    return openssl_decrypt($parts[0], 'aes-256-cbc', SECURITY_KEY, 0, $parts[1]);
}

$db = new SQLite3('a/crypto_vault.db');
$msg = "";

if (isset($_POST['save_config'])) {
    $dom = encryptData($_POST['dominio']);
    $db->exec("INSERT OR REPLACE INTO config (id, chave, valor) VALUES (1, 'dominio', '$dom')");
    $msg = "CONFIGURAÇÕES ATUALIZADAS!";
}

if (isset($_POST['add_moeda']) && !empty($_POST['moeda_nome'])) {
    $moeda = $_POST['moeda_nome'];
    $icon = $_POST['moeda_icon'] ?: 'fas fa-coins';
    $wallet = encryptData($_POST['carteira']);
    $stmt = $db->prepare("INSERT INTO vault (moeda, icone, carteira) VALUES (:m, :i, :w)");
    $stmt->bindValue(':m', $moeda);
    $stmt->bindValue(':i', $icon);
    $stmt->bindValue(':w', $wallet);
    $stmt->execute();
    $msg = "MOEDA $moeda ADICIONADA!";
}

if (isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    $db->exec("DELETE FROM vault WHERE id=$id");
    $msg = "MOEDA REMOVIDA!";
}

$moedas_registradas = $db->query("SELECT * FROM vault ORDER BY id DESC");
$dominio_atual = decryptData($db->querySingle("SELECT valor FROM config WHERE chave='dominio'"));
?>

<style>
    #content-wrapper, #content, .container-fluid, main { background-color: #06070a !important; }
    .flux-card { background: #0f111a; border-radius: 20px; border: 1px solid rgba(255,255,255,0.05); padding: 24px; margin-bottom: 20px; overflow: hidden; }
    .input-flux { background: #05060a !important; border: 1px solid #1a1b26 !important; border-radius: 12px !important; color: #fff !important; padding: 12px !important; width: 100%; font-size: 13px; outline: none !important; appearance: none; }
    .label-flux { font-weight: 900; font-size: 10px; color: #8b5cf6; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 8px; display: block; }
    .break-address { word-break: break-all; overflow-wrap: break-word; }
</style>

<main class="py-4 px-3">
    <?php if($msg): ?>
        <div class="animate__animated animate__fadeInDown bg-emerald-500/10 text-emerald-500 text-[10px] font-black p-4 rounded-xl mb-6 text-center border border-emerald-500/20 uppercase tracking-widest">
            <?php echo $msg; ?>
        </div>
    <?php endif; ?>

    <div class="flux-card border-l-4 border-l-violet-600 bg-violet-600/5">
        <h3 class="text-white font-black text-xs uppercase italic mb-2"><i class="fas fa-shield-alt mr-2 text-violet-500"></i> Gestão de Vault Cripto</h3>
        <p class="text-[10px] text-gray-400 leading-relaxed uppercase font-bold">
            As carteiras abaixo serão exibidas no seu checkout com desconto automático de 30%.
        </p>
    </div>

    <form method="POST" class="flux-card">
        <label class="label-flux">Domínio de Checkout (Whitelist)</label>
        <div class="flex flex-col md:flex-row gap-3">
            <input type="text" name="dominio" class="input-flux" placeholder="ex: meusite.com" value="<?php echo $dominio_atual; ?>" required>
            <button type="submit" name="save_config" class="bg-violet-600 hover:bg-violet-500 px-8 py-3 rounded-xl font-black text-[10px] uppercase text-white transition-all">Atualizar</button>
        </div>
    </form>

    <div class="flux-card">
        <h3 class="text-white font-black text-xs uppercase italic mb-4">Adicionar à Lista de Pagamento</h3>
        <form method="POST" class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="label-flux">Criptomoeda</label>
                <select name="moeda_nome" class="input-flux" onchange="updateIcon(this)" required>
                    <option value="">Selecione a Moeda...</option>
                    <optgroup label="Stablecoins (Mais Usadas)">
                        <option data-icon="fab fa-ethereum" value="USDT (BEP20)">USDT (Rede BSC/BEP20)</option>
                        <option data-icon="fas fa-coins" value="USDT (TRC20)">USDT (Rede TRON/TRC20)</option>
                        <option data-icon="fas fa-dollar-sign" value="USDC">USDC (USD Coin)</option>
                    </optgroup>
                    <optgroup label="Principais">
                        <option data-icon="fab fa-bitcoin" value="Bitcoin">Bitcoin (BTC)</option>
                        <option data-icon="fab fa-ethereum" value="Ethereum">Ethereum (ETH)</option>
                        <option data-icon="fas fa-bolt" value="Solana">Solana (SOL)</option>
                    </optgroup>
                    <optgroup label="Outras Redes">
                        <option data-icon="fas fa-circle" value="TRON">TRON (TRX)</option>
                        <option data-icon="fas fa-coins" value="Litecoin">Litecoin (LTC)</option>
                        <option data-icon="fas fa-dog" value="Dogecoin">Dogecoin (DOGE)</option>
                        <option data-icon="fas fa-dice-d20" value="Polygon">Polygon (MATIC)</option>
                        <option data-icon="fas fa-link" value="Chainlink">Chainlink (LINK)</option>
                        <option data-icon="fas fa-gem" value="Toncoin">Toncoin (TON)</option>
                    </optgroup>
                </select>
                <input type="hidden" name="moeda_icon" id="moeda_icon_input" value="fas fa-coins">
            </div>
            <div class="md:col-span-2">
                <label class="label-flux">Endereço da Carteira</label>
                <div class="flex gap-2">
                    <input type="text" name="carteira" class="input-flux" placeholder="Ex: 0x... ou T..." required>
                    <button type="submit" name="add_moeda" class="bg-emerald-600 hover:bg-emerald-500 px-6 rounded-xl font-black text-[10px] uppercase text-white transition-all">Ativar</button>
                </div>
            </div>
        </form>
    </div>

    <div class="flux-card">
        <h3 class="text-white font-black text-xs uppercase italic mb-4 text-emerald-500">Carteiras em Operação</h3>
        <div class="space-y-3">
            <?php while($row = $moedas_registradas->fetchArray()): ?>
            <div class="flex items-center justify-between bg-black/40 p-4 rounded-xl border border-white/5 gap-4">
                <div class="flex items-center gap-4 min-w-0"> 
                    <div class="w-10 h-10 flex-shrink-0 bg-violet-600/20 rounded-full flex items-center justify-center text-violet-500">
                        <i class="<?php echo $row['icone']; ?> fa-lg"></i>
                    </div>
                    <div class="min-w-0">
                        <p class="text-white font-black text-[11px] uppercase italic truncate"><?php echo $row['moeda']; ?></p>
                        <p class="text-[9px] text-gray-500 font-mono break-address"><?php echo decryptData($row['carteira']); ?></p>
                    </div>
                </div>
                <a href="?del=<?php echo $row['id']; ?>" class="flex-shrink-0 w-8 h-8 flex items-center justify-center rounded-lg bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white transition-all" title="Remover">
                    <i class="fas fa-trash-alt text-xs"></i>
                </a>
            </div>
            <?php endwhile; ?>
        </div>
    </div>
</main>

<script>
function updateIcon(select) {
    const icon = select.options[select.selectedIndex].getAttribute('data-icon');
    document.getElementById('moeda_icon_input').value = icon;
}
</script>

<?php include 'includes/footer.php'; ?>