<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

/* Anti-lock (recomendado) */
$db->busyTimeout(15000);
$db->exec("PRAGMA journal_mode = WAL;");
$db->exec("PRAGMA synchronous = NORMAL;");
$db->exec("PRAGMA busy_timeout = 15000;");

/* Ajuste da tabela (inclui seller e extra, que seu INSERT usa) */
$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),
    seller VARCHAR(100),
    extra VARCHAR(255)
)');

/* Se a tabela já existia sem as colunas seller/extra, tenta adicionar (não quebra se já existir) */
@$db->exec("ALTER TABLE ibo ADD COLUMN seller VARCHAR(100);");
@$db->exec("ALTER TABLE ibo ADD COLUMN extra VARCHAR(255);");

if(isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = "";
}

include 'includes/header.php';

if (isset($_POST['submit'])) {

    $usuario = trim($_POST['username'] ?? '');
    $mac_address = strtoupper(trim($_POST['mac_address'] ?? ''));

    /* ✅ BLOQUEIO DE MAC REMOVIDO COMPLETAMENTE */

    /* Mantém o bloqueio do ADM (se quiser liberar ADM, é só remover esse IF) */
    if ($usuario == "ADM") {
        echo "<script>alert('Nome de usuário inválido!');window.location.href='users.php';</script>";
        exit;
    }

    // --- LÓGICA DE DATA AUTOMÁTICA (1 ANO SE VAZIO) ---
    if (!empty($_POST['expire_date'])) {
        $we = strtotime($_POST['expire_date']);
        $ne = date('Y-m-d', $we);
    } else {
        $ne = date('Y-m-d', strtotime('+1 year'));
    }

    $start = date('Y-m-d');
    $end = date('H:i:s');
    $full = $start . 'T' . $end . '.000000Z';

    // Transação (melhor para evitar lock e garantir consistência)
    $db->exec("BEGIN IMMEDIATE;");

    try {
        $stmt = $db->prepare('
            INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, seller, extra)
            VALUES(:mac, :user, :pass, :expire, :dns, :title, :created, :seller, :extra)
        ');

        $stmt->bindValue(':mac', strtoupper($_POST['mac_address'] ?? ''), SQLITE3_TEXT);
        $stmt->bindValue(':user', $_POST['username'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(':pass', $_POST['password'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(':expire', $ne, SQLITE3_TEXT);
        $stmt->bindValue(':dns', $_POST['dns'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(':title', $_POST['title'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(':created', $full, SQLITE3_TEXT);
        $stmt->bindValue(':seller', $admin_name, SQLITE3_TEXT);
        $stmt->bindValue(':extra', $_POST['Descricao'] ?? '', SQLITE3_TEXT);

        $ok = $stmt->execute();
        if ($ok === false) {
            throw new Exception("Falha ao inserir: " . $db->lastErrorMsg());
        }
        $stmt->close();

        $db->exec("COMMIT;");
        $db->close();

        echo "<script>window.location.href='users.php';</script>";
        exit;

    } catch (Exception $e) {
        $db->exec("ROLLBACK;");
        echo "<script>alert('Erro: ".addslashes($e->getMessage())."');window.location.href='users.php';</script>";
        exit;
    }
}

$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', 'Sci-Fi Spectacle', 'Gaming Galaxy', 'Fashion Forward', 'Foodie Haven',
    'Educational Excellence', 'Anime Haven', 'Blockbuster Bonanza', 'Fitness Freaks'
];
$randomPlaylistName = $playlistNames[array_rand($playlistNames)];
?>

<style>
    :root {
        --neon-blue: #00d4ff;
        --dark-bg: #06090c;
        --card-glass: rgba(13, 18, 24, 0.95);
        --border-glass: rgba(0, 212, 255, 0.2);
    }

    body, #wrapper, #content-wrapper, #content, .container-fluid {
        background-color: var(--dark-bg) !important;
        color: #f8f9fc;
        font-family: 'Poppins', sans-serif;
    }

    .card-futuristic {
        background: var(--card-glass) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--border-glass) !important;
        border-radius: 15px !important;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        margin-bottom: 25px;
    }

    .card-header-futuristic {
        background: rgba(0, 212, 255, 0.03) !important;
        border-bottom: 1px solid var(--border-glass) !important;
        padding: 1.2rem !important;
    }

    .card-header-futuristic h6 {
        font-family: 'Orbitron', sans-serif;
        color: var(--neon-blue) !important;
        text-shadow: 0 0 10px var(--neon-blue);
        letter-spacing: 2px;
        margin: 0;
        text-transform: uppercase;
    }

    .form-control {
        background: rgba(0, 0, 0, 0.4) !important;
        border: 1px solid var(--border-glass) !important;
        color: #fff !important;
        border-radius: 8px !important;
        padding: 12px !important;
    }

    .form-control:focus {
        border-color: var(--neon-blue) !important;
        box-shadow: 0 0 15px rgba(0, 212, 255, 0.3) !important;
        color: #fff !important;
    }

    label strong {
        color: var(--neon-blue);
        font-family: 'Orbitron', sans-serif;
        font-size: 0.75rem;
        letter-spacing: 1px;
        text-transform: uppercase;
    }

    .btn-neon-success {
        background: transparent;
        border: 1px solid var(--neon-blue);
        color: var(--neon-blue) !important;
        font-family: 'Orbitron', sans-serif;
        padding: 10px 25px;
        border-radius: 8px;
        transition: 0.4s;
        text-transform: uppercase;
    }

    .btn-neon-success:hover {
        background: var(--neon-blue);
        color: #000 !important;
        box-shadow: 0 0 20px var(--neon-blue);
    }
</style>

<div class="container-fluid pt-4 px-5">
    <h1 class="h3 mb-4" style="font-family: 'Orbitron'; color: #fff;">Criar Usuário</h1>

    <div class="row">
        <div class="col-lg-12">
            <div class="card card-futuristic">
                <div class="card-header-futuristic">
                    <h6><i class="fas fa-magic mr-2"></i> M3U Extractor</h6>
                </div>
                <div class="card-body">
                    <form onsubmit="extract(event)">
                        <div class="form-group mb-0">
                            <label><strong>Link M3U</strong></label>
                            <div class="input-group">
                                <input class="form-control" id="m3u_address" placeholder="Cole o link M3U..." type="text"/>
                                <div class="input-group-append">
                                    <button class="btn btn-neon-success" type="submit">Extrair</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-12">
            <div class="card card-futuristic shadow">
                <div class="card-header-futuristic">
                    <h6><i class="fas fa-user-plus mr-2"></i> Cadastro de Usuário</h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>Endereço Mac (8 Dezenas)</strong></label>
                                    <input class="form-control" id="mac_address" name="mac_address" placeholder="a1:a2:a3:a4:a5:a6:a7:a8" type="text" value="<?php echo strtoupper($index); ?>" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>Servidor</strong></label>
                                    <input type="text" class="form-control" name="title" value="<?php echo $randomPlaylistName; ?>" required/>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>DNS</strong></label>
                                    <input type="text" class="form-control" name="dns" id="server_url" required/>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group mb-4">
                                    <label><strong>Descrição</strong></label>
                                    <input type="text" class="form-control" name="Descricao" required/>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group mb-4">
                                    <label><strong>Username</strong></label>
                                    <input type="text" class="form-control" name="username" id="username" required/>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group mb-4">
                                    <label><strong>Password</strong></label>
                                    <input type="text" class="form-control" name="password" id="password" required/>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group mb-4">
                                    <label><strong>Vencimento (Opcional)</strong></label>
                                    <input type="date" class="form-control" name="expire_date" id="datetimepicker" />
                                    <small class="text-muted">Se vazio, adiciona automaticamente 1 ano.</small>
                                </div>
                            </div>
                        </div>

                        <div class="text-right mt-4">
                            <button class="btn btn-neon-success" name="submit" type="submit">
                                <i class="fas fa-check-circle mr-2"></i> Finalizar Ativação
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// MÁSCARA MAC ADDRESS (8 PARES / 16 CARACTERES)
document.getElementById("mac_address").addEventListener("input", function(e) {
    var value = e.target.value.replace(/[^a-zA-Z0-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 && i < 15) {
            formattedValue += ":";
        }
    }
    e.target.value = formattedValue.substring(0, 23);
});

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

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>

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