<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$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))');
$res = $db->query('SELECT * FROM ibo');

if(isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = ""; // Default value
}

if(isset($_GET['update'])) {
    $user_id = $_GET['update'];
    $res1 = $db->query("SELECT * FROM ibo WHERE id = '$user_id'");
    while ($row1 = $res1->fetchArray()) {
        $user_id = $row1['id'];
        $username = $row1['username'];
        $password = $row1['password'];
        $mac_address_old = $row1['mac_address'];
        $dns = $row1['url'];
        $extra = $row1['extra'];
        $title = $row1['title'];
    }
} else {
    echo "<script>alert('Selecione o usuario a ser editado!');</script>";
    header('Location: index.php');
}

include '../includes/header2.php';

if (isset($_POST['submit'])) {
    $usuario = $_POST['username'];
    $mac_adress = strtoupper($_POST['mac_address']);
    $result = $db1->query("SELECT COUNT(*) as count FROM ibo WHERE mac_address = '$mac_adress' AND mac_address <> '$mac_address_old'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count = $row['count'];

    if($count || $usuario == "ADM") {
        echo "<script>alert('Já existe um usuario registrado com esse usuario que você esta tentando, por favor escolha outro!');window.location.href='index.php';</script>";
    } else {
        $start = date('Y-m-d');
        $end = date('h:m:s');
        $full = $start . 'T' . $end . '.000000Z';
        $mac_adress = strtoupper($_POST['mac_address']);
        $username = $_POST['username'];
        $password = $_POST['password'];
        $dns = $_POST['url'];
        $title = $_POST['title'];
        $id = $_POST['id'];
        $descricao = $_POST['Descricao'];
        $db1->exec("UPDATE ibo SET mac_address = '$mac_adress', username = '$username', password = '$password', url = '$dns', title = '$title', extra = '$descricao' WHERE id = '$id'");
    
        $db1->close();
        echo "<script>window.location.href='index.php';</script>";
    }
}
?>

<style>
/* === DESIGN FUTURISTA PARA EDIÇÃO DE USUÁRIOS === */
:root {
    --primary: #FF6B9D;
    --primary-dark: #D94A7E;
    --secondary: #00D4FF;
    --accent: #FFD166;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --text-muted: #6B7280;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(255, 107, 157, 0.3);
    --glow-accent: 0 0 20px rgba(255, 209, 102, 0.3);
}

.container-fluid {
    background: transparent !important;
    padding: 20px;
}

.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 24px;
    text-align: center;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === CARD FUTURISTA === */
.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 16px !important;
    box-shadow: var(--glow) !important;
    backdrop-filter: blur(10px);
    margin-bottom: 24px;
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(255, 107, 157, 0.4);
}

.card-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border) !important;
    border-radius: 16px 16px 0 0 !important;
    padding: 20px !important;
}

.card-header h6 {
    color: var(--text-primary) !important;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 0;
}

.card-header h6 i {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.card-body {
    padding: 30px !important;
}

/* === FORMULÁRIOS FUTURISTAS === */
.form-group {
    margin-bottom: 24px;
}

.control-label {
    color: var(--text-primary) !important;
    font-weight: 600;
    margin-bottom: 8px;
    display: block;
    font-size: 1rem;
}

.control-label strong {
    background: linear-gradient(135deg, var(--secondary), var(--primary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

.form-control {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    border-radius: 12px !important;
    color: var(--text-primary) !important;
    padding: 14px 16px;
    font-size: 1rem;
    transition: all 0.3s ease;
    width: 100%;
}

.form-control:focus {
    background: var(--surface-lighter) !important;
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.2rem rgba(255, 107, 157, 0.25) !important;
    color: var(--text-primary) !important;
    outline: none;
}

.form-control::placeholder {
    color: var(--text-muted) !important;
}

.input-group {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    align-items: stretch;
    width: 100%;
}

/* === BOTÕES FUTURISTAS === */
.btn-success {
    background: linear-gradient(135deg, var(--accent), #FFB347) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 14px 28px;
    font-weight: 600;
    font-size: 1rem;
    transition: all 0.3s ease;
    box-shadow: var(--glow-accent);
    color: var(--surface) !important;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(255, 209, 102, 0.5);
    color: var(--surface) !important;
}

.btn-icon-split {
    display: inline-flex;
    align-items: center;
    background: linear-gradient(135deg, var(--secondary), var(--primary-dark)) !important;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
    text-decoration: none;
    border: none;
}

.btn-icon-split:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
    text-decoration: none;
}

.icon {
    background: rgba(255, 255, 255, 0.2);
    padding: 12px 16px;
    display: flex;
    align-items: center;
}

.text-white-50 {
    color: rgba(255, 255, 255, 0.9) !important;
}

.btn-icon-split .text {
    padding: 12px 20px;
    font-weight: 600;
}

/* === BADGE INFORMATIVO === */
.user-info-badge {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: var(--surface);
    padding: 12px 20px;
    border-radius: 12px;
    font-size: 1rem;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 24px;
    box-shadow: var(--glow);
}

/* === ANIMAÇÕES === */
@keyframes fadeInUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.card {
    animation: fadeInUp 0.6s ease-out;
}

.form-group {
    animation: fadeInUp 0.8s ease-out;
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .container-fluid {
        padding: 10px;
    }
    
    .card-body {
        padding: 20px !important;
    }
    
    .form-control {
        padding: 12px 14px;
        font-size: 0.9rem;
    }
    
    .btn-success, .btn-icon-split {
        padding: 12px 20px;
        font-size: 0.9rem;
    }
    
    .h3 {
        font-size: 1.5rem;
    }
}

/* === GRID LAYOUT === */
.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.form-column {
    display: flex;
    flex-direction: column;
}

/* === STATUS INDICATOR === */
.status-indicator {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    background: var(--surface-lighter);
    border-radius: 8px;
    margin-bottom: 16px;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--accent);
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.5; }
    100% { opacity: 1; }
}
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">
        <i class="fas fa-user-edit"></i> Editar Usuário
    </h1>

    <!-- Badge Informativo -->
    <div class="user-info-badge">
        <i class="fas fa-info-circle"></i>
        Editando usuário ID: <?php echo $user_id; ?>
    </div>

    <!-- Card de Edição do Usuário -->
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-user-cog"></i> Configurações do Usuário
            </h6>
        </div>
        <div class="card-body">
            <form method="post">
                <!-- ID Oculto -->
                <input type="hidden" name="id" value="<?php echo $user_id; ?>">
                
                <!-- Status Indicator -->
                <div class="status-indicator">
                    <div class="status-dot"></div>
                    <span style="color: var(--text-secondary); font-size: 0.9rem;">
                        <i class="fas fa-pencil-alt"></i> Modo de edição ativo
                    </span>
                </div>

                <div class="form-row">
                    <!-- Coluna 1: Dados Principais -->
                    <div class="form-column">
                        <!-- MAC Address -->
                        <div class="form-group">
                            <label class="control-label" for="mac_address">
                                <strong>Endereço MAC</strong>
                            </label>
                            <div class="input-group">
                                <input class="form-control text-primary" id="mac_address" name="mac_address" 
                                       value="<?php echo $mac_address_old; ?>" 
                                       type="text" required/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-keyboard"></i> Formato automático: AA:BB:CC:DD:EE:FF
                            </small>
                        </div>

                        <!-- Username -->
                        <div class="form-group">
                            <label class="control-label" for="username">
                                <strong>Usuário</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="username" 
                                       value="<?php echo $username; ?>" 
                                       placeholder="Nome de usuário" required/>
                            </div>
                        </div>

                        <!-- Password -->
                        <div class="form-group">
                            <label class="control-label" for="password">
                                <strong>Senha</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="password" 
                                       value="<?php echo $password; ?>" 
                                       placeholder="Senha de acesso" required/>
                            </div>
                        </div>
                    </div>

                    <!-- Coluna 2: Configurações do Servidor -->
                    <div class="form-column">
                        <!-- DNS/URL -->
                        <div class="form-group">
                            <label class="control-label" for="url">
                                <strong>URL do Servidor</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="url" 
                                       value="<?php echo $dns; ?>" 
                                       placeholder="https://seuservidor.com" required/>
                            </div>
                        </div>

                        <!-- Descrição -->
                        <div class="form-group">
                            <label class="control-label" for="Descricao">
                                <strong>Descrição</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="Descricao" 
                                       value="<?php echo $extra; ?>" 
                                       placeholder="Descrição adicional do serviço" required/>
                            </div>
                        </div>

                        <!-- Nome do Servidor -->
                        <div class="form-group">
                            <label class="control-label" for="title">
                                <strong>Nome do Servidor</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="title" 
                                       value="<?php echo $title; ?>" 
                                       placeholder="Nome personalizado do servidor" required/>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Botões de Ação -->
                <div class="form-group text-center mt-4">
                    <div class="btn-group" role="group">
                        <button class="btn btn-success btn-icon-split" name="submit" type="submit" style="padding: 16px 40px;">
                            <span class="icon text-white-50">
                                <i class="fas fa-save"></i>
                            </span>
                            <span class="text" style="font-size: 1.1rem;">Salvar Alterações</span>
                        </button>
                        
                        <a href="index.php" class="btn btn-icon-split" style="background: var(--surface-lighter); color: var(--text-primary); margin-left: 12px; text-decoration: none;">
                            <span class="icon text-white-50">
                                <i class="fas fa-arrow-left"></i>
                            </span>
                            <span class="text">Voltar</span>
                        </a>
                    </div>
                </div>

                <!-- Aviso de Validação -->
                <div style="background: var(--surface-lighter); border: 1px solid var(--border); border-radius: 10px; padding: 16px; margin-top: 20px;">
                    <div style="color: var(--accent); font-weight: 600; margin-bottom: 8px;">
                        <i class="fas fa-shield-alt"></i> Validação de Dados
                    </div>
                    <div style="color: var(--text-secondary); font-size: 0.9rem;">
                        Todas as alterações são validadas automaticamente. Certifique-se de que o MAC Address e Username são únicos no sistema.
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Formatação automática do MAC Address
document.addEventListener("DOMContentLoaded", function() {
    var macAddressInput = document.getElementById("mac_address");

    macAddressInput.addEventListener("input", function(e) {
        var value = e.target.value;
        value = value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();

        var formattedValue = "";
        for (var i = 0; i < value.length; i++) {
            formattedValue += value[i];
            if ((i + 1) % 2 === 0 && i < value.length - 1) {
                formattedValue += ":";
            }
        }

        e.target.value = formattedValue;
    });

    // Efeito de foco nos campos ao carregar
    const inputs = document.querySelectorAll('.form-control');
    inputs.forEach((input, index) => {
        input.style.animationDelay = `${index * 0.1}s`;
    });
});

// Validação do formulário
document.querySelector('form').addEventListener('submit', function(e) {
    const macAddress = document.getElementById('mac_address').value;
    const username = document.querySelector('input[name="username"]').value;
    
    // Validação básica do MAC Address
    const macRegex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/;
    if (!macRegex.test(macAddress)) {
        e.preventDefault();
        showNotification('Formato de MAC Address inválido!', 'error');
        return;
    }
    
    // Validação do username
    if (username.trim() === 'ADM') {
        e.preventDefault();
        showNotification('Username "ADM" não é permitido!', 'error');
        return;
    }
});

// Função de notificação
function showNotification(message, type) {
    // Criar elemento de notificação
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'error' ? 'linear-gradient(135deg, #FF4757, #FF3742)' : 'linear-gradient(135deg, var(--accent), #FFB347)'};
        color: var(--surface);
        padding: 16px 20px;
        border-radius: 12px;
        box-shadow: var(--glow);
        z-index: 10000;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 10px;
        animation: slideIn 0.3s ease-out;
    `;
    
    notification.innerHTML = `
        <i class="fas ${type === 'error' ? 'fa-exclamation-triangle' : 'fa-check-circle'}"></i>
        ${message}
    `;
    
    document.body.appendChild(notification);
    
    // Remover após 5 segundos
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-in';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 5000);
}

// Animação CSS para notificações
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(style);
</script>

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