<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('a/.eggziedb.db');
$db1 = $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'];
        $expire_date = $row1['expire_date'];
        $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: users.php');
}

include 'includes/header.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='users.php';</script>";
    } else {
        $we = strtotime($_POST['expire_date']);
        $ne = date('Y-m-d', $we);
        $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', expire_date = '$ne', url = '$dns', title = '$title', extra = '$descricao' WHERE id = '$id'");
        $db1->close();
        echo "<script>window.location.href='users.php';</script>";
    }
}
?>

<style>
/* === DESIGN FUTURISTA MODERNO === */
:root {
    --primary: #00D4FF;
    --primary-dark: #0099CC;
    --secondary: #FF6B9D;
    --accent: #00FF88;
    --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(0, 212, 255, 0.3);
    --glow-accent: 0 0 20px rgba(0, 255, 136, 0.3);
}

/* === FUNDO FUTURISTA === */
body {
    background: linear-gradient(135deg, #0A0F1C 0%, #151B2D 50%, #0A0F1C 100%) !important;
    font-family: 'Inter', sans-serif !important;
    min-height: 100vh;
    color: var(--text-primary);
    overflow-x: hidden;
}

/* Efeito de partículas futuristas */
body::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: 
        radial-gradient(circle at 20% 80%, rgba(0, 212, 255, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 80% 20%, rgba(255, 107, 157, 0.1) 0%, transparent 50%),
        radial-gradient(circle at 40% 40%, rgba(0, 255, 136, 0.05) 0%, transparent 50%);
    pointer-events: none;
    z-index: -1;
}

/* === CONTAINER PRINCIPAL === */
.container-fluid {
    background: transparent !important;
    padding: 20px;
}

/* === CARD FUTURISTA === */
.card {
    background: var(--surface-light) !important;
    border: 1px solid var(--border) !important;
    border-radius: 20px !important;
    box-shadow: 0 8px 40px rgba(0,0,0,0.4) !important;
    color: var(--text-primary) !important;
    overflow: hidden;
    backdrop-filter: blur(20px);
}

.card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: borderGlow 3s ease-in-out infinite;
}

@keyframes borderGlow {
    0%, 100% { opacity: 0.7; }
    50% { opacity: 1; }
}

.card-header {
    background: linear-gradient(135deg, var(--surface-light), var(--surface-lighter)) !important;
    border-bottom: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    padding: 20px !important;
    font-size: 1.2rem;
}

.card-body {
    background: transparent !important;
    color: var(--text-primary) !important;
    padding: 30px !important;
}

/* === TÍTULO PRINCIPAL === */
.h3 {
    color: var(--text-primary) !important;
    font-weight: 700 !important;
    margin-bottom: 20px !important;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
}

/* === FORMULÁRIO FUTURISTA === */
.form-group {
    margin-bottom: 25px;
}

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

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

.form-control:focus {
    border-color: var(--primary) !important;
    box-shadow: 0 0 0 0.3rem rgba(0, 212, 255, 0.25) !important;
    background: var(--surface-lighter) !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ÃO FUTURISTA === */
.btn-success {
    background: linear-gradient(135deg, var(--accent), #00CC77) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: var(--glow-accent) !important;
    padding: 14px 28px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: white !important;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 10px;
}

.btn-success:hover {
    transform: translateY(-3px) !important;
    box-shadow: 0 8px 25px rgba(0, 255, 136, 0.5) !important;
    color: white !important;
}

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

.btn-icon-split:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0, 212, 255, 0.5);
    color: white !important;
    text-decoration: none;
}

/* === ÍCONES === */
.fas {
    color: currentColor !important;
}

/* === ANIMAÇÃO DE PARTÍCULAS === */
@keyframes moveParticles {
    from { transform: translateY(0); opacity: 0.7; }
    to { transform: translateY(-1000px); opacity: 0; }
}

.particle {
    position: fixed;
    bottom: 0;
    width: 2px;
    height: 2px;
    background: var(--primary);
    opacity: 0.5;
    animation: moveParticles linear infinite;
    z-index: -1;
}

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

/* === ESTILOS ESPECÍFICOS DO FORMULÁRIO === */
.text-primary {
    color: var(--text-primary) !important;
}

strong {
    color: var(--text-primary) !important;
    font-weight: 600;
}

/* Campo MAC Address com formatação especial */
#mac_address {
    font-family: 'Courier New', monospace;
    font-weight: 600;
    letter-spacing: 1px;
}

/* Campo de data */
#datepicker {
    background: var(--surface-lighter) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-primary) !important;
}
</style>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Partículas animadas
    const numParticles = 20;
    const particlesContainer = document.createElement('div');
    particlesContainer.style.position = 'fixed';
    particlesContainer.style.top = '0';
    particlesContainer.style.left = '0';
    particlesContainer.style.width = '100%';
    particlesContainer.style.height = '100%';
    particlesContainer.style.pointerEvents = 'none';
    particlesContainer.style.zIndex = '-1';
    
    for (let i = 0; i < numParticles; i++) {
        const particle = document.createElement('div');
        particle.classList.add('particle');
        particle.style.left = Math.random() * 100 + 'vw';
        particle.style.animationDuration = (2 + Math.random() * 8) + 's';
        particle.style.animationDelay = Math.random() * 10 + 's';
        particle.style.width = particle.style.height = (1 + Math.random() * 3) + 'px';
        particlesContainer.appendChild(particle);
    }
    
    document.body.appendChild(particlesContainer);

    // Formatação automática do MAC Address
    var macAddressInput = document.getElementById("mac_address");
    
    if (macAddressInput) {
        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 do formulário
    const formInputs = document.querySelectorAll('.form-control');
    formInputs.forEach(input => {
        input.addEventListener('focus', function() {
            this.style.transform = 'scale(1.02)';
            this.style.boxShadow = '0 0 20px rgba(0, 212, 255, 0.3)';
        });
        
        input.addEventListener('blur', function() {
            this.style.transform = 'scale(1)';
            this.style.boxShadow = 'none';
        });
    });
});

function extract(event) {
    event.preventDefault();
    var m3uLink = document.getElementById("m3u_address").value;
    var serverUrl = m3uLink.split("/get.php")[0];
    document.getElementById("server_url").value = serverUrl;
    var username = getParameterByName("username", m3uLink);
    document.getElementById("username").value = username;
    var password = getParameterByName("password", m3uLink);
    document.getElementById("password").value = password;
}

function getParameterByName(name, url) {
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return "";
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</script>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">🔄 Atualizar Usuário</h1>
    
    <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">
                <i class="fas fa-user-edit"></i> Editar Usuário
            </h6>
        </div>
        <div class="card-body">
            <form method="post">
                <input type="hidden" name="id" value="<?php echo $user_id; ?>">
                
                <div class="form-group">
                    <label class="control-label" for="mac_address">
                        <i class="fas fa-network-wired"></i> <strong>Mac Address</strong>
                    </label>
                    <input class="form-control" id="mac_address" name="mac_address" 
                           value="<?php echo $mac_address_old; ?>" type="text" required 
                           placeholder="00:1A:2B:3C:4D:5E"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="username">
                        <i class="fas fa-user"></i> <strong>Username</strong>
                    </label>
                    <input type="text" class="form-control" name="username" 
                           value="<?php echo $username; ?>" required 
                           placeholder="Nome de usuário"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="password">
                        <i class="fas fa-lock"></i> <strong>Password</strong>
                    </label>
                    <input type="text" class="form-control" name="password" 
                           value="<?php echo $password; ?>" required 
                           placeholder="Senha do usuário"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="expire_date">
                        <i class="fas fa-calendar-alt"></i> <strong>Data de Expiração</strong>
                    </label>
                    <input type="text" class="form-control" name="expire_date" 
                           value="<?php echo $expire_date; ?>" id="datepicker" 
                           placeholder="YYYY-MM-DD"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="dns">
                        <i class="fas fa-server"></i> <strong>DNS</strong>
                    </label>
                    <input type="text" class="form-control" name="url" 
                           value="<?php echo $dns; ?>" required 
                           placeholder="URL do servidor"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="Descricao">
                        <i class="fas fa-sticky-note"></i> <strong>Descrição</strong>
                    </label>
                    <input type="text" class="form-control" name="Descricao" 
                           value="<?php echo $extra; ?>" id="Descricao" required 
                           placeholder="Descrição do usuário"/>
                </div>
                
                <div class="form-group">
                    <label class="control-label" for="title">
                        <i class="fas fa-tag"></i> <strong>Nome do Servidor</strong>
                    </label>
                    <input type="text" class="form-control" name="title" 
                           value="<?php echo $title; ?>" required 
                           placeholder="Nome do servidor"/>
                </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-check"></i>
                        </span>
                        <span class="text">Atualizar Usuário</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>

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