<?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/header2.php';

if (isset($_POST['submit'])) {
    $meses = $_POST['expire_date'];
    $db1 = new SQLite3('../a/.eggziedb.db');
    $result = $db1->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
    while ($row = $result->fetchArray()) {
        $macs = $row['macs'];
        break;
    }
     
    if($macs < $meses) {
        echo "<script>alert('Você não possui MACs suficientes!');window.location.href='index.php';</script>";
    } else {
        $usuario = $_POST['username'];
        $mac_address = strtoupper($_POST['mac_address']);
        $result = $db1->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='index.php';</script>";
        } else {
            if($meses <= 0 || $meses > 999) {
                echo "<script>alert('Numero de meses invalido!');window.location.href='index.php';</script>";
            } else {
                $currentDate = date('Y-m-d');
                $ne = date('Y-m-d', strtotime("+$meses years", strtotime($currentDate)));
                $start = date('Y-m-d');
                $end = date('h:m:s');
                $full = $start . 'T' . $end . '.000000Z';
                $db1->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 . '\',\'' . $seller_name . '\', \''.$_POST['Descricao'].'\')');
                $newmac = $macs - $meses;
                $db1->exec("UPDATE revenda SET macs = '$newmac' WHERE usuario = '$seller_name'");
                $db1->close();
                echo "<script>window.location.href='index.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>
/* === DESIGN FUTURISTA PARA CRIAÇÃ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;
}

/* === CARDS FUTURISTAS === */
.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%;
}

.input-group-append {
    margin-left: -1px;
}

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

/* === INDICADOR DE MACS === */
.mac-counter {
    background: var(--surface-lighter);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 20px;
    margin: 20px 0;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.mac-counter::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent));
}

.mac-counter h4 {
    color: var(--text-primary);
    margin-bottom: 8px;
    font-weight: 600;
}

.mac-counter .current-macs {
    font-size: 2rem;
    font-weight: 700;
    background: linear-gradient(135deg, var(--accent), var(--primary));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    margin: 10px 0;
}

/* === ALERTAS E AVISOS === */
.warning-alert {
    background: linear-gradient(135deg, rgba(255, 107, 157, 0.1), rgba(255, 209, 102, 0.1));
    border: 1px solid var(--primary);
    border-radius: 12px;
    padding: 16px 20px;
    margin: 20px 0;
    color: var(--text-primary);
    position: relative;
}

.warning-alert::before {
    content: '⚠️';
    position: absolute;
    left: 20px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1.5rem;
}

.warning-alert-content {
    margin-left: 50px;
}

.warning-alert strong {
    color: var(--accent);
}

/* === 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;
    }
    
    .warning-alert::before {
        position: static;
        transform: none;
        margin-bottom: 8px;
        display: block;
    }
    
    .warning-alert-content {
        margin-left: 0;
    }
}

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

/* === BADGE INFORMATIVO === */
.info-badge {
    background: linear-gradient(135deg, var(--secondary), 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);
}
</style>

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

    <!-- Informações do Revendedor -->
    <?php
    $result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
    $current_macs = 0;
    while ($row = $result->fetchArray()) {
        $current_macs = $row['macs'];
        break;
    }
    ?>
    
    <div class="mac-counter">
        <h4><i class="fas fa-coins"></i> Seus Créditos MACs Disponíveis</h4>
        <div class="current-macs"><?php echo $current_macs; ?> MACs</div>
        <small style="color: var(--text-muted);">Total disponível para distribuição</small>
    </div>

    <!-- Card de Criaçã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">
                <!-- Aviso Importante -->
                <div class="warning-alert">
                    <div class="warning-alert-content">
                        <strong>Atenção:</strong> O número de anos selecionado será descontado do seu saldo de MACs!
                    </div>
                </div>

                <div class="form-row">
                    <!-- Coluna 1: Dados Básicos -->
                    <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" 
                                       placeholder="00:1A:2B:3C:4D:5E" 
                                       type="text" value="<?php echo strtoupper($index); ?>" 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>

                        <!-- 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" 
                                       placeholder="Nome personalizado do servidor" 
                                       id="discription" value="<?php echo $randomPlaylistName; ?>" required/>
                            </div>
                        </div>

                        <!-- DNS/URL -->
                        <div class="form-group">
                            <label class="control-label" for="dns">
                                <strong>URL do Servidor</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control text-primary" name="dns" 
                                       placeholder="https://seuservidor.com" 
                                       id="server_url" required/>
                            </div>
                        </div>
                    </div>

                    <!-- Coluna 2: Credenciais -->
                    <div class="form-column">
                        <!-- 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" 
                                       placeholder="Descrição adicional do serviço" 
                                       id="Descricao" required/>
                            </div>
                        </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" 
                                       placeholder="Nome de usuário" 
                                       id="username" 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" 
                                       placeholder="Senha de acesso" 
                                       id="password" required/>
                            </div>
                        </div>

                        <!-- Anos de Validade -->
                        <div class="form-group">
                            <label class="control-label" for="expire_date">
                                <strong>Duração da Assinatura (Anos)</strong>
                            </label>
                            <div class="input-group">
                                <input type="number" placeholder="Número de anos" 
                                       class="form-control text-primary" name="expire_date" 
                                       id="expire_date" value="1" min="1" max="999" 
                                       style="text-align: center; font-weight: 600;"/>
                            </div>
                            <small style="color: var(--text-muted); margin-top: 4px; display: block;">
                                <i class="fas fa-info-circle"></i> 1 ano = 1 crédito MAC
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Resumo da Criação -->
                <div class="mac-counter" style="background: rgba(0, 212, 255, 0.1);">
                    <h4><i class="fas fa-calculator"></i> Resumo da Criação</h4>
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-top: 15px;">
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">MACs Atuais</div>
                            <div style="color: var(--text-primary); font-size: 1.5rem; font-weight: 700;"><?php echo $current_macs; ?></div>
                        </div>
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">MACs a Distribuir</div>
                            <div style="color: var(--accent); font-size: 1.5rem; font-weight: 700;" id="macs-to-distribute">1</div>
                        </div>
                        <div style="text-align: center;">
                            <div style="color: var(--text-secondary); font-size: 0.9rem;">Saldo Restante</div>
                            <div style="color: var(--primary); font-size: 1.5rem; font-weight: 700;" id="remaining-macs"><?php echo $current_macs - 1; ?></div>
                        </div>
                    </div>
                </div>

                <!-- Botão de Submissão -->
                <div class="form-group text-center mt-4">
                    <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-rocket"></i>
                        </span>
                        <span class="text" style="font-size: 1.1rem;">Ativar Usuário</span>
                    </button>
                </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;
    });
});

// Atualização dinâmica do contador de MACs
document.addEventListener('DOMContentLoaded', function() {
    var inputElement = document.getElementById("expire_date");
    var currentMacs = <?php echo $current_macs; ?>;
    var macsToDistribute = document.getElementById("macs-to-distribute");
    var remainingMacs = document.getElementById("remaining-macs");
    
    function handleKeyDown(event) {
        var value = inputElement.value;
        if(value != '') {
            if(value <= 0) {
                value = 1;
            }
            if(value > 999) {
                value = 999;
            }
            inputElement.value = value;
        } else {
            value = '?';
        }
        
        macsToDistribute.textContent = value;
        remainingMacs.textContent = currentMacs - value;
        
        // Efeito visual
        macsToDistribute.style.transform = "scale(1.1)";
        remainingMacs.style.transform = "scale(1.1)";
        setTimeout(() => {
            macsToDistribute.style.transform = "scale(1)";
            remainingMacs.style.transform = "scale(1)";
        }, 200);
    }

    inputElement.addEventListener("input", handleKeyDown);
    inputElement.addEventListener("change", handleKeyDown);
    
    // Inicializar
    handleKeyDown();
});

// Validação do formulário
document.querySelector('form').addEventListener('submit', function(e) {
    const username = document.getElementById('username').value.trim();
    const macsValue = parseInt(document.getElementById('expire_date').value);
    const currentMacs = <?php echo $current_macs; ?>;
    
    // Validação do username
    if (username.toUpperCase() === 'ADM') {
        e.preventDefault();
        alert('Username "ADM" não é permitido!');
        return;
    }
    
    // Validação dos MACs
    if (macsValue > currentMacs) {
        e.preventDefault();
        alert('Número de anos excede seu saldo de MACs disponível!');
        return;
    }
    
    if (macsValue < 1) {
        e.preventDefault();
        alert('Número de anos deve ser maior que zero!');
        return;
    }
    
    // Confirmação adicional
    if (!confirm('Confirma a criação deste usuário?\n\nEsta ação irá consumir ' + macsValue + ' créditos MACs do seu saldo.')) {
        e.preventDefault();
    }
});
</script>

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