<?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
}

include 'includes/header.php';

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

    if($count || $usuario == "ADM") {
      echo "<script>alert('Já existe um usuario registrado com esse MAC 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';
    	$db->exec('INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, seller, extra) VALUES(\'' . strtoupper($_POST['mac_address']) . '\', \'' . $_POST['username'] . '\', \'' . $_POST['password'] . '\', \'' . $ne . '\', \'' . $_POST['dns'] . '\', \'' . $_POST['title'] . '\',\'' . $full . '\', \'' . $admin_name. '\', \'' . $_POST['Descricao']. '\')');
    	$db->close();
      echo "<script>window.location.href='users.php';</script>";
    }
}

$playlistNames = [
    'Ultimate Entertainment',
    'Global TV Hub',
    'Prime Streaming Zone',
    'All-in-One IPTV Lounge',
    'HD Channel Showcase',
    'Sports Mania',
    'Movie Magic',
    'News Network Central',
    'Kids Fun Zone',
    'Lifestyle Paradise',
    'Documentary Delight',
    'Music Melodies',
    'Comedy Central',
    'Reality TV Extravaganza',
    'Traveler\'s Guide',
    'Sci-Fi Spectacle',
    'Health and Fitness Channel',
    'Gaming Galaxy',
    'Fashion Forward',
    'Business Buzz',
    'Foodie Haven',
    'Educational Excellence',
    'Thriller Theater',
    'History Channel Vault',
    'Cartoons Unlimited',
    'Tech Titans',
    'Wildlife Adventure',
    'Artistic Expressions',
    'Supernatural Secrets',
    'Retro Rewind',
    'Romance Reels',
    'Spiritual Serenity',
    'DIY Network',
    'Car Enthusiast\'s Paradise',
    'Action Packed',
    'True Crime Stories',
    'International Flavor',
    'Nature\'s Wonders',
    'Home Makeover Madness',
    'Anime Haven',
    'Pop Culture Playground',
    'Hidden Gems',
    'Blockbuster Bonanza',
    'Motivational Mojo',
    'Vintage Vibes',
    'Outdoor Expeditions',
    'Social Media Stars',
    'Celebrity Showcase',
    'Science and Technology Marvels',
    'Fitness Freaks'
];

$randomPlaylistName = $playlistNames[array_rand($playlistNames)];
?>

<style>
/* === ESTILOS ESPECÍFICOS PARA ATIVAÇÃO DE USUÁRIO FUTURISTA === */
.main-content {
    background: transparent !important;
    padding: 20px;
}

.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;
    position: relative;
    margin-bottom: 25px;
}

.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;
}

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

/* Formulários futuristas */
.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;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.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;
    transform: translateY(-2px);
}

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

/* Botões futuristas */
.btn-success {
    background: linear-gradient(135deg, var(--accent), #00cc7a) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: var(--glow-accent) !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
    text-transform: uppercase;
    letter-spacing: 1px;
}

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

.btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    box-shadow: var(--glow) !important;
    padding: 12px 24px !important;
    font-weight: 600 !important;
    transition: all 0.3s ease !important;
}

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

/* Labels e textos */
.control-label {
    color: var(--text-primary) !important;
    font-weight: 600;
    margin-bottom: 10px;
    display: block;
    font-size: 1rem;
}

.text-primary2 {
    color: var(--primary) !important;
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    font-size: 1.3rem !important;
}

/* Títulos */
.h3 {
    color: var(--text-primary) !important;
    font-weight: 700;
    margin-bottom: 20px;
}

/* Input group */
.input-group {
    margin-bottom: 20px;
    border-radius: 12px !important;
    overflow: hidden;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.input-group .form-control {
    border-radius: 12px 0 0 12px !important;
    border-right: none !important;
}

.input-group-append .btn {
    border-radius: 0 12px 12px 0 !important;
    border-left: none !important;
}

/* Ícones */
.fa-user, .fa-expand, .fa-check {
    margin-right: 8px;
}

/* Efeito 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;
}

.particle:nth-child(odd) { background: var(--accent); }

/* Botões de ação */
.btn-icon-split {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark)) !important;
    border: none !important;
    border-radius: 12px !important;
    padding: 12px 20px !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;
}

/* Responsividade */
@media (max-width: 768px) {
    .main-content {
        padding: 10px !important;
    }
    
    .card-body {
        padding: 20px !important;
    }
    
    .btn-success, .btn-primary {
        padding: 10px 20px !important;
        font-size: 0.9rem !important;
    }
    
    .form-control {
        padding: 12px 15px !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);

        // Efeitos nos inputs
        const inputs = document.querySelectorAll('.form-control');
        inputs.forEach(input => {
            input.addEventListener('focus', function() {
                this.style.transform = 'translateY(-2px)';
            });
            
            input.addEventListener('blur', function() {
                this.style.transform = 'translateY(0)';
            });
        });
    });

    // Formatação 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;
        });
    });

    // Extrator M3U
    function extract(event) {
        event.preventDefault();

        var m3uLink = document.getElementById("m3u_address").value;

        // Extract server URL
        var serverUrl = m3uLink.split("/get.php")[0];
        document.getElementById("server_url").value = serverUrl;

        // Extract username
        var username = getParameterByName("username", m3uLink);
        document.getElementById("username").value = username;

        // Extract password
        var password = getParameterByName("password", m3uLink);
        document.getElementById("password").value = password;
        
        // Mostrar feedback visual
        const extractBtn = document.getElementById("extract_button");
        extractBtn.innerHTML = '<i class="fas fa-check"></i> Extraído!';
        extractBtn.style.background = 'linear-gradient(135deg, var(--accent), #00cc7a)';
        
        setTimeout(() => {
            extractBtn.innerHTML = '<i class="fas fa-expand"></i> Extrair';
        }, 2000);
    }

    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>

<main role="main" class="col-12 pt-4 px-4 main-content">
    <div class="container-fluid">
        <h1 class="h3 mb-4 text-gray-800">
            <i class="fas fa-user-plus me-2"></i>Ativar Usuário
        </h1>
        
        <!-- Card do Extrator M3U -->
        <div class="row">
            <div class="col-lg-8">
                <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-primary2">
                            <i class="fas fa-link me-2"></i>Extrator M3U
                        </h6>
                    </div>
                    <div class="card-body">
                        <form>
                            <div class="form-group">
                                <label class="control-label" for="m3u_address">
                                    <i class="fas fa-file-alt me-2"></i><strong>Link M3U</strong>
                                </label>
                                <div class="input-group">
                                    <input class="form-control" id="m3u_address" name="m3u_address" placeholder="Cole o link M3U completo aqui..." type="text" required/>
                                    <div class="input-group-append">
                                        <button class="btn btn-primary btn-icon-split" id="extract_button" onclick="extract(event)">
                                            <span class="icon text-white-50">
                                                <i class="fas fa-expand"></i>
                                            </span>
                                            <span class="text">Extrair</span>
                                        </button>
                                    </div>
                                </div>
                                <small class="text-muted">Cole o link M3U para extrair automaticamente servidor, usuário e senha.</small>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card de Detalhes do Usuário -->
        <div class="row">
            <div class="col-lg-8">
                <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-primary2">
                            <i class="fas fa-user-cog me-2"></i>Detalhes do Usuário
                        </h6>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="form-group">
                                <label class="control-label" for="mac_address">
                                    <i class="fas fa-network-wired me-2"></i><strong>Endereço MAC</strong>
                                </label>
                                <div class="input-group">
                                    <input class="form-control" id="mac_address" name="mac_address" placeholder="00:1A:2B:3C:4D:5E" type="text" value="<?php echo strtoupper($index); ?>" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="title">
                                    <i class="fas fa-server me-2"></i><strong>Nome do Servidor</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="title" placeholder="Nome personalizado do servidor" id="discription" value="<?php echo $randomPlaylistName; ?>" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="dns">
                                    <i class="fas fa-globe me-2"></i><strong>URL do Servidor</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="dns" placeholder="https://seuservidor.com" id="server_url" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="Descricao">
                                    <i class="fas fa-info-circle me-2"></i><strong>Descrição</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="Descricao" placeholder="Descrição ou observações" id="Descricao" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="username">
                                    <i class="fas fa-user me-2"></i><strong>Usuário</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="username" placeholder="Nome de usuário" id="username" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="password">
                                    <i class="fas fa-lock me-2"></i><strong>Senha</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="password" placeholder="Senha de acesso" id="password" required/>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label class="control-label" for="expire_date">
                                    <i class="fas fa-calendar-alt me-2"></i><strong>Data de Expiração</strong>
                                </label>
                                <div class="input-group">
                                    <input type="text" placeholder="AAAA-MM-DD" class="form-control" name="expire_date" id="datetimepicker" required/>
                                </div>
                            </div>
                            
                            <div class="form-group mt-4">
                                <div>
                                    <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                                        <span class="icon text-white-50">
                                            <i class="fas fa-play-circle"></i>
                                        </span>
                                        <span class="text">Ativar Usuário</span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

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

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