<?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 `sub_revenda` (
    `id` INTEGER PRIMARY KEY,
    `nome` TEXT NOT NULL,
    `usuario` TEXT NOT NULL,
    `senha` TEXT NOT NULL,
    `registro` TIMESTAMP NOT NULL,
    `macs` INTEGER NOT NULL,
    `registrado_por` TEXT NOT NULL,
    `extra` TEXT,
    `id_ref` INTEGER
);');

include 'includes/header.php';
$admin_name = $_SESSION['admin_name'] ?? 'ADMIN';

// Verificar se há mensagem de sucesso na sessão
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']); // Limpar a mensagem após exibir
}

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

    $result = $db->query("SELECT COUNT(*) as count FROM sub_revenda WHERE usuario = '$usuario'");
    $row = $result->fetchArray(SQLITE3_ASSOC);
    $count2 = $row['count'];

    $count = $count + $count2;

    if ($count || $usuario == "ADM") {
        echo "<script>
            alert('Já existe um sub revenda/revenda com esse usuário, por favor escolha outro!');
            window.location.href = 'sub_revenda.php';
        </script>";
        exit;
    } else {
        $registro = date('Y/m/d');
        $nome = $_POST['nome'];
        $senha = $_POST['password'];
        $macs = $_POST['macs'];
        $Descricao = $_POST['Descricao'];

        $query = "SELECT MAX(max_value) AS maior_valor FROM (
            SELECT MAX(id_ref) AS max_value FROM revenda
            UNION
            SELECT MAX(id_ref) AS max_value FROM sub_revenda
        ) as combined";
        $result = $db->query($query);
        $row = $result->fetchArray(SQLITE3_ASSOC);
        $ref_id = $row['maior_valor'];
        $ref_id++;

        $db->exec("INSERT INTO sub_revenda(nome, usuario, senha, registro, macs, registrado_por, extra, id_ref) VALUES('$nome', '$usuario', '$senha', '$registro', '$macs', '$admin_name', '$Descricao', '$ref_id')");
        
        // 🔥🔥🔥 GERAR E SALVAR E-MAIL NEPSTER PARA SUB-REVENDA
        $nepster_email = '';
        try {
            // Gerar email Nepster
            $usuario_limpo = preg_replace('/[^a-zA-Z0-9]/', '', $usuario);
            $nepster_email = strtolower($usuario_limpo) . "@nepster.xyz";
            
            if (empty($usuario_limpo)) {
                $nepster_email = "user_" . $ref_id . "@nepster.xyz";
            }

            // Salvar no banco de emails de sub-revenda
            $nepster_db_path = __DIR__ . '/a/.nepster_subemails.db';
            $nepster_db = new SQLite3($nepster_db_path);

            // Criar tabela se não existir
            $nepster_db->exec('CREATE TABLE IF NOT EXISTS emails (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                email TEXT UNIQUE,
                tipo TEXT,
                usuario TEXT UNIQUE,
                id_ref INTEGER UNIQUE,
                criado_em TEXT,
                status TEXT DEFAULT "ativo"
            )');

            // Deletar registro existente se houver
            $nepster_db->exec("DELETE FROM emails WHERE usuario = '$usuario'");
            
            // Inserir novo email
            $stmt = $nepster_db->prepare("INSERT INTO emails (email, tipo, usuario, id_ref, criado_em)
                                          VALUES (?, ?, ?, ?, ?)");
            $stmt->bindValue(1, $nepster_email, SQLITE3_TEXT);
            $stmt->bindValue(2, 'subrevenda', SQLITE3_TEXT);
            $stmt->bindValue(3, $usuario, SQLITE3_TEXT);
            $stmt->bindValue(4, $ref_id, SQLITE3_INTEGER);
            $stmt->bindValue(5, date('Y-m-d H:i:s'), SQLITE3_TEXT);
            $stmt->execute();
            
            $nepster_db->close();
            
        } catch (Exception $e) {
            error_log("Erro ao salvar email Nepster: " . $e->getMessage());
        }

        $db->close();

        // criar arquivos padrão:
        $base = "a/rtx/";
        @copy($base . "Setting.json", $base . "Setting_$usuario.json");
        @copy($base . "logo_filenames.json", $base . "logo_filenames_$usuario.json");
        @copy($base . "image_filenames.json", $base . "image_filenames_$usuario.json");
        @copy("a/note.json", "a/note_$usuario.json");
        @copy("a/qrcode.json", "a/qrcode_$usuario.json");
        @copy("api/theme.json", "api/theme_$usuario.json");

        // Salvar mensagem de sucesso na sessão e redirecionar
        $_SESSION['success_message'] = "Subrevenda criada com sucesso!\\nE-mail Nepster: $nepster_email";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Nova Subrevenda - ULTRA IBO</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
:root {
    --primary: #00D4FF;
    --primary-dark: #0099CC;
    --secondary: #FF6B9D;
    --accent: #00FF88;
    --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);
}
body {
    background: radial-gradient(circle at center, #0a0a0f, #000);
    font-family: "Inter", sans-serif;
    color: var(--text-primary);
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow-x: hidden;
    margin: 0;
    padding: 20px;
}
.form-container {
    background: rgba(10, 15, 28, 0.85);
    backdrop-filter: blur(20px);
    border: 1px solid var(--border);
    border-radius: 24px;
    padding: 40px;
    width: 100%;
    max-width: 1200px;
    box-shadow: var(--glow), 0 8px 32px rgba(0,0,0,0.3);
    text-align: center;
    position: relative;
    overflow: hidden;
}
.form-container::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 3px;
    background: linear-gradient(90deg, var(--primary), var(--accent), var(--secondary));
    animation: moveGradient 3s linear infinite;
}
@keyframes moveGradient { 0%,100%{opacity:0.7;} 50%{opacity:1;} }
h1 {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    text-transform: uppercase;
    font-weight: 700;
    margin-bottom: 30px;
    text-shadow: 0 0 15px rgba(0, 212, 255, 0.4);
}
label {
    display: block;
    text-align: left;
    font-weight: 600;
    color: var(--text-secondary);
    margin-bottom: 8px;
    margin-top: 20px;
}
input {
    width: 100%;
    padding: 14px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--surface-lighter);
    color: var(--text-primary);
    font-size: 1rem;
    transition: all 0.3s ease;
}
input:focus {
    border-color: var(--primary);
    box-shadow: var(--glow);
    outline: none;
}
.btn-submit {
    background: linear-gradient(135deg, var(--primary), var(--accent));
    border: none;
    border-radius: 12px;
    padding: 16px 24px;
    color: white;
    font-size: 1.1rem;
    font-weight: 700;
    margin-top: 30px;
    cursor: pointer;
    text-transform: uppercase;
    letter-spacing: 1px;
    transition: all 0.3s ease;
    width: 100%;
}
.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 0 25px rgba(0, 212, 255, 0.6);
}
.glow-border {
    position: absolute;
    inset: -2px;
    border-radius: 26px;
    background: linear-gradient(135deg, var(--primary), var(--accent), var(--secondary));
    z-index: -1;
    filter: blur(12px);
    opacity: 0.4;
}
.particle {
    position: fixed;
    bottom: 0;
    width: 2px; height: 2px;
    background: var(--primary);
    opacity: 0.5;
    animation: floatParticles linear infinite;
    z-index: -2;
}
@keyframes floatParticles {
    from { transform: translateY(0); opacity: 0.7; }
    to { transform: translateY(-1000px); opacity: 0; }
}
.success-message {
    background: rgba(0, 255, 136, 0.1);
    border: 1px solid #00FF88;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 30px;
    text-align: center;
    animation: fadeIn 0.5s ease;
}
.success-message h3 {
    color: #00FF88;
    margin: 0 0 10px 0;
    font-size: 1.2rem;
}
.success-message p {
    margin: 5px 0;
    color: var(--text-primary);
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(-10px); }
    to { opacity: 1; transform: translateY(0); }
}
</style>
</head>
<body>
<div class="form-container">
    <div class="glow-border"></div>
    
    <?php if (isset($success_message)): ?>
    <div class="success-message">
        <h3><i class="fas fa-check-circle"></i> Sucesso!</h3>
        <p><?php echo str_replace("\\n", "<br>", htmlspecialchars($success_message)); ?></p>
    </div>
    <?php endif; ?>
    
    <h1><i class="fas fa-user-plus"></i> Nova Subrevenda</h1>
    <form method="post">
        <label for="nome"><i class="fa-solid fa-user"></i> Nome</label>
        <input type="text" id="nome" name="nome" placeholder="Digite o nome completo" required>

        <label for="macs"><i class="fa-solid fa-microchip"></i> MACs</label>
        <input type="number" id="macs" name="macs" placeholder="Número de MACs" min="1" max="99999" required>

        <label for="username"><i class="fa-solid fa-id-card"></i> Usuário</label>
        <input type="text" id="username" name="username" placeholder="Escolha o nome de usuário" required>

        <label for="password"><i class="fa-solid fa-lock"></i> Senha</label>
        <input type="text" id="password" name="password" placeholder="Digite uma senha segura" required>

        <label for="Descricao"><i class="fa-solid fa-note-sticky"></i> Descrição</label>
        <input type="text" id="Descricao" name="Descricao" placeholder="Digite uma descrição (opcional)" required>

        <button class="btn-submit" name="submit" type="submit">
            <i class="fas fa-check-circle"></i> Criar Subrevenda
        </button>
    </form>
</div>

<script>
document.addEventListener("DOMContentLoaded", () => {
    const numParticles = 60;
    for (let i = 0; i < numParticles; i++) {
        const p = document.createElement("div");
        p.className = "particle";
        p.style.left = Math.random() * 100 + "vw";
        p.style.animationDuration = (2 + Math.random() * 8) + "s";
        p.style.animationDelay = Math.random() * 5 + "s";
        document.body.appendChild(p);
    }

    // Prevenir reenvio do formulário ao recarregar a página
    if (window.history.replaceState) {
        window.history.replaceState(null, null, window.location.href);
    }

    // Auto-remover mensagem de sucesso após 5 segundos
    const successMessage = document.querySelector('.success-message');
    if (successMessage) {
        setTimeout(() => {
            successMessage.style.opacity = '0';
            successMessage.style.transform = 'translateY(-10px)';
            setTimeout(() => {
                successMessage.remove();
            }, 500);
        }, 5000);
    }
});
</script>
</body>
</html>