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

$db = new SQLite3('./a/.eggziedb.db');

// Criar tabela se não existir
$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))');

$update_data = null;

// Tentar carregar dados por ID (vindo de users.php) ou por MAC (vindo de devices.php)
if (isset($_GET['update'])) {
    $id = (int)$_GET['update'];
    $res = $db->query("SELECT * FROM ibo WHERE id = $id");
    $update_data = $res->fetchArray(SQLITE3_ASSOC);
} elseif (isset($_GET['mac'])) {
    $mac = strtoupper(trim($_GET['mac']));
    $res = $db->query("SELECT * FROM ibo WHERE UPPER(mac_address) = '$mac'");
    $update_data = $res->fetchArray(SQLITE3_ASSOC);
}

// Processar formulário de atualização
if (isset($_POST['submit'])) {
    $id = (int)$_POST['id'];
    $mac = strtoupper(trim($_POST['mac_address']));
    $user = $_POST['username'];
    $pass = $_POST['password'];
    $dns = $_POST['dns'];
    $title = $_POST['title'];
    $expire = date('Y-m-d', strtotime($_POST['expire_date']));

    $db->exec("UPDATE ibo SET 
        mac_address = '$mac', 
        username = '$user', 
        password = '$pass', 
        url = '$dns', 
        title = '$title', 
        expire_date = '$expire' 
        WHERE id = $id");
    
    $db->close();
    header('Location: users.php');
    exit();
}

include 'includes/header.php';
?>

<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Editar Usuário</h1>
    
    <?php if (!$update_data): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-triangle mr-2"></i>
            Usuário não encontrado ou não cadastrado ainda.
        </div>
        <a href="users.php" class="btn btn-primary">Voltar para Lista</a>
    <?php else: ?>
        <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-edit mr-2"></i> Detalhes do Usuário</h6>
            </div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" name="id" value="<?php echo $update_data['id']; ?>">
                    
                    <div class="form-group">
                        <label><strong>Endereço MAC</strong></label>
                        <input class="form-control text-primary" id="mac_address" name="mac_address" type="text" value="<?php echo htmlspecialchars($update_data['mac_address']); ?>" required/>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Nome do Servidor</strong></label>
                        <input type="text" class="form-control text-primary" name="title" value="<?php echo htmlspecialchars($update_data['title']); ?>" required/>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>DNS</strong></label>
                        <input type="text" class="form-control text-primary" name="dns" value="<?php echo htmlspecialchars($update_data['url']); ?>" required/>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Usuário</strong></label>
                        <input type="text" class="form-control text-primary" name="username" value="<?php echo htmlspecialchars($update_data['username']); ?>" required/>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Senha</strong></label>
                        <input type="text" class="form-control text-primary" name="password" value="<?php echo htmlspecialchars($update_data['password']); ?>" required/>
                    </div>
                    
                    <div class="form-group">
                        <label><strong>Data de Expiração</strong></label>
                        <input type="text" placeholder="YYYY-MM-DD" class="form-control text-primary" name="expire_date" id="datetimepicker" value="<?php echo $update_data['expire_date']; ?>"/>
                    </div>
                    
                    <div class="form-group">
                        <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                            <span class="icon text-white-50"><i class="fas fa-save"></i></span>
                            <span class="text">Salvar Alterações</span>
                        </button>
                        <a href="users.php" class="btn btn-secondary btn-icon-split ml-2">
                            <span class="icon text-white-50"><i class="fas fa-times"></i></span>
                            <span class="text">Cancelar</span>
                        </a>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    var macInput = document.getElementById("mac_address");
    macInput.addEventListener("input", function(e) {
        var v = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
        var f = "";
        for (var i = 0; i < v.length; i++) {
            f += v[i];
            if ((i + 1) % 2 === 0 && i < v.length - 1) f += ":";
        }
        e.target.value = f;
    });
});
</script>

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