<?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 você usa no INSERT) */
$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, 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/header2.php';

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

    $meses = (int)($_POST['expire_date'] ?? 0);

    // Pega saldo de MACs do revendedor
    $stmt = $db->prepare("SELECT macs FROM revenda WHERE usuario = :u LIMIT 1");
    $stmt->bindValue(":u", $seller_name, SQLITE3_TEXT);
    $rs = $stmt->execute();
    $row = $rs->fetchArray(SQLITE3_ASSOC);
    $rs->finalize();
    $stmt->close();

    $macs = (int)($row['macs'] ?? 0);

    if ($macs < $meses) {
        echo "<script>alert('Você não possui MACs suficientes!');window.location.href='index.php';</script>";
        exit;
    }

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

    // Mantém a regra do ADM (se quiser liberar ADM também, é só remover esse IF)
    if ($usuario === "ADM") {
        echo "<script>alert('Username ADM não é permitido!');window.location.href='index.php';</script>";
        exit;
    }

    if ($meses <= 0 || $meses > 999) {
        echo "<script>alert('Numero de meses invalido!');window.location.href='index.php';</script>";
        exit;
    }

    // Datas
    $currentDate = date('Y-m-d');
    $ne = date('Y-m-d', strtotime("+$meses years", strtotime($currentDate)));
    $full = date('Y-m-d\TH:i:s.000000\Z');

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

    try {
        // ✅ IMPORTANTE: REMOVIDO o bloqueio de MAC repetido
        // Agora permite criar quantos usuários quiser com o mesmo mac_address.

        $stmt = $db->prepare("
            INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, seller, extra)
            VALUES(:mac, :user, :pass, :exp, :url, :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(":exp", $ne, SQLITE3_TEXT);
        $stmt->bindValue(":url", $_POST['dns'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(":title", $_POST['title'] ?? '', SQLITE3_TEXT);
        $stmt->bindValue(":created", $full, SQLITE3_TEXT);
        $stmt->bindValue(":seller", $seller_name, SQLITE3_TEXT);
        $stmt->bindValue(":extra", $_POST['Descricao'] ?? '', SQLITE3_TEXT);

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

        // Desconta macs do revendedor
        $stmt = $db->prepare("
            UPDATE revenda
            SET macs = macs - :qtd
            WHERE usuario = :u AND macs >= :qtd
        ");
        $stmt->bindValue(":qtd", $meses, SQLITE3_INTEGER);
        $stmt->bindValue(":u", $seller_name, SQLITE3_TEXT);

        $ok2 = $stmt->execute();
        if ($ok2 === false) {
            throw new Exception("Falha no UPDATE: " . $db->lastErrorMsg());
        }
        $stmt->close();

        if ($db->changes() < 1) {
            throw new Exception("Saldo insuficiente (concorrência).");
        }

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

        $db->close();
        echo "<script>window.location.href='index.php';</script>";
        exit;

    } catch (Exception $e) {
        $db->exec("ROLLBACK;");
        echo "<script>alert('Erro ao criar: ".addslashes($e->getMessage())."');window.location.href='index.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'];
$randomPlaylistName = $playlistNames[array_rand($playlistNames)];
?>

<style>
    @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&family=Poppins:wght@300;400;600&display=swap');

    :root {
        --neon-emerald: #00ff88;
        --neon-gold: #ffcc00;
        --dark-bg: #050a0e;
        --glass-bg: rgba(255, 255, 255, 0.02);
        --glass-border: rgba(0, 255, 136, 0.15);
    }

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

    .h3 {
        font-family: 'Orbitron', sans-serif;
        color: #fff !important;
        text-transform: uppercase;
        letter-spacing: 2px;
        text-shadow: 0 0 10px rgba(0, 255, 136, 0.3);
    }

    .card-futuristic {
        background: var(--glass-bg) !important;
        backdrop-filter: blur(15px);
        border: 1px solid var(--glass-border) !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, 255, 136, 0.03) !important;
        border-bottom: 1px solid var(--glass-border) !important;
        padding: 1.2rem !important;
    }

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

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

    .form-control:focus {
        border-color: var(--neon-emerald) !important;
        box-shadow: 0 0 15px rgba(0, 255, 136, 0.2) !important;
    }

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

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

    .btn-emerald:hover {
        background: var(--neon-emerald);
        color: #000 !important;
        box-shadow: 0 0 20px var(--neon-emerald);
    }

    #gasto {
        font-family: 'Orbitron', sans-serif;
        font-size: 0.85rem;
        display: block;
        margin-top: 15px;
        text-shadow: 0 0 5px rgba(255,0,0,0.3);
    }

    .input-group-append .btn {
        border-radius: 0 8px 8px 0 !important;
    }
</style>

<div class="container-fluid pt-4 px-5">
    <h1 class="h3 mb-4">Activate User</h1>

    <div class="card card-futuristic shadow">
        <div class="card-header-futuristic">
            <h6><i class="fas fa-magic mr-2"></i> M3U Extractor</h6>
        </div>
        <div class="card-body">
            <form>
                <div class="form-group mb-0">
                    <label><strong>M3U Link</strong></label>
                    <div class="input-group">
                        <input class="form-control" id="m3u_address" placeholder="Enter M3U Link" type="text" required/>
                        <div class="input-group-append">
                            <button class="btn btn-emerald" type="button" onclick="extract(event)">
                                <i class="fa fa-expand mr-1"></i> Extract
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="card card-futuristic shadow">
        <div class="card-header-futuristic">
            <h6><i class="fas fa-user-plus mr-2"></i> User Details</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>Mac Address</strong></label>
                            <input class="form-control" id="mac_address" name="mac_address" placeholder="00:00:00:00:00:00" type="text" value="<?php echo strtoupper($index); ?>" required/>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group mb-4">
                            <label><strong>Server Name</strong></label>
                            <input type="text" class="form-control" name="title" id="discription" 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" placeholder="http://server.com:8080" required/>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group mb-4">
                            <label><strong>Description</strong></label>
                            <input type="text" class="form-control" name="Descricao" id="Descricao" placeholder="Additional notes" 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" placeholder="User ID" 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" placeholder="User Pass" required/>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group mb-4">
                            <label><strong>Validity (Years)</strong></label>
                            <input type="number" class="form-control" name="expire_date" id="expire_date" value="1" min="1" max="999"/>
                        </div>
                    </div>
                </div>

                <div class="mt-4">
                    <button class="btn btn-emerald" name="submit" type="submit">
                        <i class="fas fa-check-circle mr-2"></i> Submit Registration
                    </button>
                    <b style="color:var(--neon-gold);" id="gasto">A criação desse usuario irá consumir 1 MAC</b>
                </div>
            </form>
        </div>
    </div>
</div>

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

var inputElement = document.getElementById("expire_date");
function handleKeyDown() {
    var value = inputElement.value;
    if(value != '') {
        if(value <= 0) value = 1;
        if(value > 999) value = 999;
        inputElement.value = value;
    } else {
        value = '?';
    }
    document.getElementById("gasto").innerText = 'A criação desse usuario irá consumir ' + value + ' MAC';
}
inputElement.addEventListener("input", handleKeyDown);
</script>

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