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

if (isset($_POST['submit'])) {
    
     $meses = $_POST['expire_date'];
     $db1 = new SQLite3('../a/.eggziedb.db');
     $result = $db1->query("SELECT macs FROM sub_revenda WHERE usuario = '$seller_name'");
     // Iterate over the fetched results
     while ($row = $result->fetchArray()) {
         // Output the value of the column
         $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');
                    // Add 5 months
                    $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 sub_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>
:root {
    --primary: #00D4FF;
    --primary-dark: #00A3CC;
    --secondary: #FF6B9D;
    --surface: #0A0F1C;
    --surface-light: #1A1F2C;
    --surface-lighter: #2A2F3C;
    --text-primary: #FFFFFF;
    --text-secondary: #B0B7C3;
    --border: rgba(255,255,255,0.1);
    --glow: 0 0 20px rgba(0, 212, 255, 0.3);
}

/* === DESIGN FUTURISTA PARA A PÁGINA === */
body {
    background: var(--surface) !important;
    color: var(--text-primary);
    font-family: 'Inter', sans-serif;
}

.container-fluid {
    padding: 20px;
}

.card {
    background: var(--surface-light);
    border-radius: 16px;
    border: 1px solid var(--border);
    margin-bottom: 20px;
    padding: 0;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
    border-color: var(--primary);
}

.card-header {
    background: var(--surface-lighter);
    padding: 20px;
    border-bottom: 1px solid var(--border);
    border-radius: 16px 16px 0 0;
    position: relative;
}

.card-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, var(--primary), transparent);
}

.card-body {
    padding: 30px;
}

/* === BOTÕES FUTURISTAS === */
.btn-primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border: none;
    border-radius: 10px;
    color: white;
    padding: 12px 24px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: var(--glow);
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(0, 212, 255, 0.5);
    color: white;
}

.btn-success {
    background: linear-gradient(135deg, #10B981, #059669);
    border: none;
    border-radius: 10px;
    color: white;
    padding: 12px 24px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 0 20px rgba(16, 185, 129, 0.3);
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 30px rgba(16, 185, 129, 0.5);
    color: white;
}

/* === FORMULÁRIOS FUTURISTAS === */
.form-control {
    background: var(--surface-lighter);
    border: 2px solid var(--border);
    border-radius: 10px;
    color: var(--text-primary);
    padding: 12px 16px;
    width: 100%;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: var(--primary);
    outline: none;
    box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.1);
}

.form-group label {
    color: var(--text-primary);
    font-weight: 600;
    margin-bottom: 8px;
    font-size: 0.9rem;
}

.input-group {
    position: relative;
}

.input-group-append .btn {
    border-radius: 0 10px 10px 0;
    border-left: 1px solid var(--border);
}

/* === INDICADOR DE MACS === */
.mac-counter {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    padding: 8px 16px;
    border-radius: 10px;
    font-weight: 600;
    display: inline-block;
    margin-bottom: 20px;
    box-shadow: var(--glow);
}

.text-primary2 {
    color: var(--primary) !important;
    font-weight: 700;
}

/* === ALERTAS E INFORMAÇÕES === */
.alert-info {
    background: rgba(0, 212, 255, 0.1);
    border: 1px solid var(--primary);
    border-radius: 10px;
    color: var(--text-primary);
    padding: 15px;
    margin-bottom: 20px;
}

.cost-indicator {
    background: linear-gradient(135deg, #F59E0B, #D97706);
    color: white;
    padding: 12px 20px;
    border-radius: 10px;
    font-weight: 600;
    text-align: center;
    margin-top: 20px;
    box-shadow: 0 0 20px rgba(245, 158, 11, 0.3);
}

/* === RESPONSIVIDADE === */
@media (max-width: 768px) {
    .container-fluid {
        padding: 10px;
    }
    
    .card-body {
        padding: 20px;
    }
    
    .btn {
        width: 100%;
        margin-bottom: 10px;
    }
    
    .input-group {
        flex-direction: column;
    }
    
    .input-group-append .btn {
        border-radius: 10px;
        border-left: none;
        border-top: 1px solid var(--border);
        margin-top: 10px;
    }
}
</style>

<script>
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;
    });
});

function extract(event) {
  event.preventDefault(); // Prevent page refresh

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

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, " "));
}

// Atualizar contador de MACs gastos
function updateMacCost() {
    var inputElement = document.getElementById("expire_date");
    var value = inputElement.value;
    
    if(value === '' || value <= 0) {
        value = 1;
        inputElement.value = value;
    }
    
    if(value > 999) {
        value = 999;
        inputElement.value = value;
    }
    
    var costElement = document.getElementById("gasto");
    costElement.innerHTML = `<i class="fas fa-coins mr-2"></i>A criação desse usuário irá consumir <strong>${value} MAC${value > 1 ? 's' : ''}</strong>`;
}

document.addEventListener("DOMContentLoaded", function() {
    var inputElement = document.getElementById("expire_date");
    inputElement.addEventListener("input", updateMacCost);
    inputElement.addEventListener("change", updateMacCost);
    
    // Inicializar contador
    updateMacCost();
});
</script>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">
        <i class="fas fa-user-plus mr-2"></i>Criar Novo Usuário
    </h1>
    
    <!-- Card do Extrator M3U -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2">
                <i class="fas fa-link mr-2"></i>Extrator M3U
            </h6>
        </div>
        <div class="card-body">
            <form>
                <div class="form-group">
                    <label class="control-label" for="m3u_address">
                        <strong>Link M3U</strong>
                    </label>
                    <div class="input-group">
                        <input class="form-control" id="m3u_address" name="m3u_address" 
                               placeholder="🔗 Cole o link M3U aqui..." type="text" required/>
                        <div class="input-group-append">
                            <button class="btn btn-success" id="extract_button" onclick="extract(event)">
                                <i class="fas fa-expand-arrows-alt mr-2"></i>Extrair
                            </button>
                        </div>
                    </div>
                    <small class="text-muted">Cole o link M3U para extrair automaticamente as credenciais</small>
                </div>
            </form>
        </div>
    </div>

    <!-- Card de Detalhes do Usuário -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary2">
                <i class="fas fa-user-circle mr-2"></i>Detalhes do Usuário
            </h6>
        </div>
        <div class="card-body">
            <form method="post">
                <!-- Linha 1: Mac Address e Nome do Servidor -->
                <div class="row">
                    <div class="col-md-6">
                        <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" id="mac_address" name="mac_address" 
                                       placeholder="🔢 Digite o endereço MAC" type="text" 
                                       value="<?php echo strtoupper($index); ?>" required/>
                            </div>
                            <small class="text-muted">Formato automático: AA:BB:CC:DD:EE:FF</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <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" name="title" 
                                       placeholder="🏷️ Nome do servidor" id="discription" 
                                       value="<?php echo $randomPlaylistName; ?>" required/>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Linha 2: DNS e Descrição -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label" for="dns">
                                <strong>DNS/URL do Servidor</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="dns" 
                                       placeholder="🌐 URL do servidor" id="server_url" required/>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <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" name="Descricao" 
                                       placeholder="📝 Descrição adicional" id="Descricao" required/>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Linha 3: Username e Password -->
                <div class="row">
                    <div class="col-md-6">
                        <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" name="username" 
                                       placeholder="👤 Nome de usuário" id="username" required/>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label" for="password">
                                <strong>Senha</strong>
                            </label>
                            <div class="input-group">
                                <input type="text" class="form-control" name="password" 
                                       placeholder="🔒 Senha do usuário" id="password" required/>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Linha 4: Anos de Validade -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label" for="expire_date">
                                <strong>Anos de Validade</strong>
                            </label>
                            <div class="input-group">
                                <input type="number" placeholder="📅 Número de anos" 
                                       class="form-control" name="expire_date" id="expire_date" 
                                       value="1" min="1" max="999" required/>
                                <div class="input-group-append">
                                    <span class="input-group-text">ano(s)</span>
                                </div>
                            </div>
                            <small class="text-muted">1 ano = 1 MAC credit</small>
                        </div>
                    </div>
                </div>

                <!-- Indicador de Custo -->
                <div class="cost-indicator" id="gasto">
                    <i class="fas fa-coins mr-2"></i>
                    A criação desse usuário irá consumir 1 MAC
                </div>

                <!-- Botão de Submissão -->
                <div class="form-group mt-4">
                    <button class="btn btn-success btn-lg" name="submit" type="submit">
                        <i class="fas fa-check-circle mr-2"></i>
                        <span class="text">Criar Usuário</span>
                    </button>
                    <a href="index.php" class="btn btn-secondary btn-lg ml-2">
                        <i class="fas fa-arrow-left mr-2"></i>
                        Voltar
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

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