<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


function getIPAddress() {
    $ip = 'undefined';
    if (isset($_SERVER)) {
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
    } else {
        $ip = getenv('REMOTE_ADDR');
        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
    }
    $ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
    return $ip;
}

session_start();

// Carregar informações do arquivo JSON
$info = json_decode(file_get_contents('./includes/eggzie.json'), true);
$aa = $info['info']['aa'];

// Criar ou abrir banco de dados SQLite
$db = new SQLite3('./a/.eggziepanels.db');
$db->exec('CREATE TABLE IF NOT EXISTS USERS(id INT PRIMARY KEY, NAME TEXT, USERNAME TEXT, PASSWORD TEXT, LOGO TEXT)');

// Verificar se não há usuários e inserir um usuário padrão
$userCountQuery = $db->query('SELECT COUNT(*) as count FROM USERS');
$userCount = $userCountQuery->fetchArray()['count'];
if ($userCount == 0) {
    $db->exec('INSERT INTO USERS(id, NAME, USERNAME, PASSWORD, LOGO) VALUES(\'1\', \'Your Name\', \'admin\', \'admin\', \'img/logo.png\')');
}

// Obter dados do usuário padrão
$userQuery = $db->query('SELECT * FROM USERS WHERE id=\'1\'');
$user = $userQuery->fetchArray();
$userName = $user['NAME'];
$userLogo = $user['LOGO'];

function LoginReseller($usernamee, $password) {
    $db = new SQLite3('./a/.eggziedb.db');
    $query = 'SELECT * FROM sub_revenda WHERE usuario="' . $usernamee . '"';
    $result = $db->query($query);
    
    while ($row = $result->fetchArray()) {
        $revendaId = $row['id'];
        $name = $row['nome'];
        $usuario = $row['usuario'];
        $passwordFromDB = $row['senha'];
    }

    if (empty($revendaId)) {
        $errorMessage = '<div class="neon-alert neon-alert-danger">NÃO É UM USUÁRIO VÁLIDO!</div>';
        echo $errorMessage;
    } else if ($passwordFromDB == $password) {
        $_SESSION['eggzie_iboPlayer3'] = true;
        $_SESSION['reseller_name'] = $usuario;
        $_SESSION['aviso_reseller'] = false;
        $_SESSION['id'] = $revendaId;
        header('Location: sub_revenda/index.php');
    } else {
        $errorMessage = '<div class="neon-alert neon-alert-danger">SENHA INCORRETA!</div>';
        echo $errorMessage;
    }

    $db->close();
}

function LoginSeller($usernamee, $password) {
    $db = new SQLite3('./a/.eggziedb.db');
    $query = 'SELECT * FROM revenda WHERE usuario="' . $usernamee . '"';
    $result = $db->query($query);
    
    while ($row = $result->fetchArray()) {
        $revendaId = $row['id'];
        $name = $row['nome'];
        $usuario = $row['usuario'];
        $passwordFromDB = $row['senha'];
    }

    if (empty($revendaId)) {
         LoginReseller($usernamee, $password);
    } else if ($passwordFromDB == $password) {
        $_SESSION['eggzie_iboPlayer2'] = true;
        $_SESSION['seller_name'] = $usuario;
        $_SESSION['aviso_seller'] = false;
        $_SESSION['id'] = $revendaId;
        header('Location: revenda/index.php');
    } else {
         LoginReseller($usernamee, $password);
    }

    $db->close();
}

// Verificar login
if (isset($_POST['login'])) {
    $usernamee = $_POST['username'];
    $password = $_POST['password'];

    $query = 'SELECT * FROM USERS WHERE USERNAME="' . $usernamee . '"';
    $result = $db->query($query);
    
    while ($row = $result->fetchArray()) {
        $userId = $row['id'];
        $name = $row['NAME'];
        $username = $row['USERNAME'];
        $passwordFromDB = $row['PASSWORD'];
        $logo = $row['LOGO'];
    }

    if (empty($userId)) {
        LoginSeller($usernamee, $password);
    } else if ($passwordFromDB == $password) {
        $_SESSION['eggzie_iboPlayer'] = true;
        $_SESSION['name'] = $userName;
        $_SESSION['logo'] = $userLogo;
        header('Location: dashboard.php');
    } else {
        LoginSeller($usernamee, $password);
    }

    $db->close();
}

// Gravar log de acesso
$date = date('d-m-Y H:i:s');
$ipAddress = getIPAddress();
$logDb = new SQLite3('./a/.logs.db');
$logDb->exec('CREATE TABLE IF NOT EXISTS logs(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date TEXT, ipaddress TEXT)');
$logDb->exec('INSERT INTO logs(date, ipaddress) VALUES(\'' . $date . '\', \'' . $ipAddress . '\')');

// Criar ou abrir outro banco de dados SQLite
$dataDb = new SQLite3('./a/.eggziedb.db');
$dataDb->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY AUTOINCREMENT 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))');
$dataDb->exec('CREATE TABLE IF NOT EXISTS theme(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(100), url VARCHAR(100))');

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IBO NOTIFICATION - LOGIN</title>
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link rel="icon" href="favicon.ico" type="image/x-icon">

    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --secondary: #10b981;
            --accent: #f59e0b;
            --danger: #ef4444;
            --dark-bg: #0f172a;
            --dark-surface: #1e293b;
            --dark-surface-light: #334155;
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --text-muted: #64748b;
            --border: rgba(255, 255, 255, 0.1);
            --glass-bg: rgba(30, 41, 59, 0.7);
            --glass-border: rgba(255, 255, 255, 0.05);
            --glow: 0 0 20px rgba(99, 102, 241, 0.3);
            --glow-strong: 0 0 40px rgba(99, 102, 241, 0.5);
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: linear-gradient(135deg, var(--dark-bg) 0%, #1e293b 50%, #0f172a 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow-x: hidden;
            padding: 20px;
        }
        
        /* Elementos de fundo animados */
        .bg-grid {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: 
                linear-gradient(var(--border) 1px, transparent 1px),
                linear-gradient(90deg, var(--border) 1px, transparent 1px);
            background-size: 50px 50px;
            mask-image: radial-gradient(circle at center, black 20%, transparent 80%);
            opacity: 0.1;
            z-index: -2;
        }
        
        .floating-elements {
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            pointer-events: none;
            z-index: -1;
        }
        
        .floating-element {
            position: absolute;
            border-radius: 50%;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            opacity: 0.1;
            filter: blur(20px);
        }
        
        .floating-element:nth-child(1) {
            width: 300px;
            height: 300px;
            top: 10%;
            left: 5%;
            animation: float 25s infinite ease-in-out;
        }
        
        .floating-element:nth-child(2) {
            width: 200px;
            height: 200px;
            bottom: 15%;
            right: 10%;
            animation: float 20s infinite ease-in-out reverse;
        }
        
        .floating-element:nth-child(3) {
            width: 150px;
            height: 150px;
            top: 40%;
            right: 15%;
            animation: float 18s infinite ease-in-out;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0) rotate(0deg); }
            33% { transform: translateY(-30px) rotate(120deg); }
            66% { transform: translateY(20px) rotate(240deg); }
        }
        
        /* Container principal */
        .login-container {
            width: 100%;
            max-width: 420px;
            position: relative;
            z-index: 10;
        }
        
        .neon-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 24px;
            border: 1px solid var(--glass-border);
            box-shadow: 
                0 10px 40px rgba(0, 0, 0, 0.4),
                inset 0 1px 0 rgba(255, 255, 255, 0.1);
            padding: 40px;
            position: relative;
            overflow: hidden;
            transition: all 0.5s ease;
        }
        
        .neon-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--secondary), var(--accent));
            border-radius: 24px 24px 0 0;
        }
        
        .neon-card::after {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(
                45deg,
                transparent 0%,
                rgba(99, 102, 241, 0.1) 50%,
                transparent 100%
            );
            animation: shine 8s infinite linear;
            z-index: -1;
        }
        
        @keyframes shine {
            0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
            100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
        }
        
        /* Logo */
        .logo-container {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .logo-neon {
            width: 180px;
            height: 100px;
            object-fit: contain;
            filter: drop-shadow(0 0 15px rgba(99, 102, 241, 0.5));
            transition: all 0.3s ease;
        }
        
        .logo-neon:hover {
            transform: scale(1.05);
            filter: drop-shadow(0 0 25px rgba(99, 102, 241, 0.7));
        }
        
        /* Títulos */
        .neon-title {
            font-size: 2.5rem;
            font-weight: 800;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            text-align: center;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }
        
        .neon-subtitle {
            color: var(--text-secondary);
            text-align: center;
            font-size: 1.1rem;
            margin-bottom: 30px;
            font-weight: 400;
        }
        
        /* Formulário (inicialmente oculto) */
        .login-form {
            max-height: 0;
            overflow: hidden;
            opacity: 0;
            transition: all 0.8s ease;
        }
        
        .login-form.show {
            max-height: 500px;
            opacity: 1;
            margin-top: 20px;
        }
        
        .neon-input-group {
            margin-bottom: 25px;
            position: relative;
        }
        
        .neon-input {
            width: 100%;
            padding: 18px 20px;
            background: rgba(15, 23, 42, 0.6);
            border: 2px solid rgba(99, 102, 241, 0.2);
            border-radius: 14px;
            color: var(--text-primary);
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
            outline: none;
        }
        
        .neon-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1), var(--glow);
            background: rgba(15, 23, 42, 0.8);
            transform: translateY(-2px);
        }
        
        .neon-input::placeholder {
            color: var(--text-muted);
        }
        
        .input-icon {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
            font-size: 18px;
        }
        
        /* Botões */
        .neon-btn {
            width: 100%;
            padding: 18px;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            border: none;
            border-radius: 14px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            position: relative;
            overflow: hidden;
            box-shadow: var(--glow);
        }
        
        .access-btn {
            margin-top: 20px;
            background: linear-gradient(135deg, var(--accent), #eab308);
        }
        
        .access-btn:hover {
            background: linear-gradient(135deg, #f59e0b, #ca8a04);
        }
        
        .neon-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.7s ease;
        }
        
        .neon-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 15px 30px rgba(99, 102, 241, 0.4);
        }
        
        .neon-btn:hover::before {
            left: 100%;
        }
        
        .neon-btn:active {
            transform: translateY(-1px);
        }
        
        /* Alertas */
        .neon-alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            font-weight: 600;
            text-align: center;
            border: 1px solid transparent;
            backdrop-filter: blur(10px);
        }
        
        .neon-alert-danger {
            background: rgba(239, 68, 68, 0.2);
            border-color: rgba(239, 68, 68, 0.3);
            color: #fca5a5;
            box-shadow: 0 0 20px rgba(239, 68, 68, 0.2);
        }
        
        /* Rodapé */
        .login-footer {
            margin-top: 30px;
            text-align: center;
            color: var(--text-muted);
            font-size: 14px;
        }
        
        .developer-link {
            color: var(--primary);
            text-decoration: none;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .developer-link:hover {
            color: var(--secondary);
            text-shadow: 0 0 10px rgba(16, 185, 129, 0.5);
        }
        
        /* Texto de boas-vindas */
        .welcome-text {
            color: var(--text-secondary);
            text-align: center;
            font-size: 1.1rem;
            margin-bottom: 30px;
            line-height: 1.6;
            min-height: 90px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .typewriter-container {
            display: inline-block;
            text-align: center;
        }
        
        .typewriter-text {
            display: inline-block;
            overflow: hidden;
            white-space: nowrap;
            border-right: 2px solid var(--primary);
            animation: blink-caret 0.75s step-end infinite;
            font-weight: 500;
            color: var(--text-primary);
            font-size: 1.2rem;
        }
        
        @keyframes blink-caret {
            from, to { border-color: transparent; }
            50% { border-color: var(--primary); }
        }
        
        /* Responsividade */
        @media (max-width: 768px) {
            .neon-card {
                padding: 30px 25px;
            }
            
            .neon-title {
                font-size: 2rem;
            }
            
            .logo-neon {
                width: 150px;
                height: 80px;
            }
            
            .neon-input {
                padding: 16px;
                font-size: 16px;
            }
            
            body {
                padding: 15px;
            }
            
            .typewriter-text {
                font-size: 1.1rem;
            }
            
            .welcome-text {
                min-height: 80px;
                font-size: 1rem;
            }
        }
        
        @media (max-width: 480px) {
            .neon-card {
                padding: 25px 20px;
            }
            
            .neon-title {
                font-size: 1.8rem;
            }
            
            .logo-neon {
                width: 120px;
                height: 60px;
            }
            
            .floating-elements {
                display: none;
            }
            
            .typewriter-text {
                font-size: 1rem;
                white-space: normal;
            }
            
            .welcome-text {
                min-height: 70px;
            }
        }
        
        /* Efeito de pulse no botão */
        @keyframes pulse {
            0% { box-shadow: var(--glow); }
            50% { box-shadow: var(--glow-strong); }
            100% { box-shadow: var(--glow); }
        }
        
        .access-btn {
            animation: pulse 2s infinite;
        }
        
        /* Efeito de loading */
        .loading {
            pointer-events: none;
            opacity: 0.8;
        }
        
        .loading::after {
            content: '';
            width: 20px;
            height: 20px;
            border: 2px solid transparent;
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* Animação de entrada */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-in {
            animation: fadeInUp 0.8s ease forwards;
        }
        
        /* Animação de saída */
        @keyframes fadeOutUp {
            from {
                opacity: 1;
                transform: translateY(0);
            }
            to {
                opacity: 0;
                transform: translateY(-30px);
            }
        }
        
        .animate-out {
            animation: fadeOutUp 0.8s ease forwards;
        }
    </style>
</head>
<body>
    <div class="bg-grid"></div>
    
    <div class="floating-elements">
        <div class="floating-element"></div>
        <div class="floating-element"></div>
        <div class="floating-element"></div>
    </div>
    
    <div class="login-container">
        <div class="neon-card" id="mainCard">
            <!-- Logo -->
            <div class="logo-container">
                <img src="<?php echo $userLogo; ?>" class="logo-neon" alt="IBO REVENDA Logo">
            </div>
            
            <!-- Títulos -->
            <h1 class="neon-title">IBO NOTIFICATION</h1>
            <p class="neon-subtitle"><?php echo htmlspecialchars($userName); ?></p>
            
            <!-- Texto de boas-vindas com efeito typewriter -->
            <div class="welcome-text" id="welcomeText">
                <div class="typewriter-container">
                    <span id="typewriter" class="typewriter-text"></span>
                </div>
            </div>
            
            <!-- Botão Acesso Restrito -->
            <button type="button" id="accessBtn" class="neon-btn access-btn">
                <i class="fas fa-lock"></i>
                ACESSO RESTRITO
            </button>
            
            <!-- Mensagens de erro -->
            <?php 
            // Exibir mensagens de erro se existirem
            if (isset($errorMessage)) {
                echo '<div id="errorMessage">' . $errorMessage . '</div>';
            }
            ?>
            
            <!-- Formulário de Login (inicialmente oculto) -->
            <div class="login-form" id="loginForm">
                <form method="post" id="loginFormElement">
                    <div class="neon-input-group">
                        <input type="text" 
                               class="neon-input" 
                               name="username" 
                               placeholder="Username" 
                               required>
                        <div class="input-icon">
                            <i class="fas fa-user"></i>
                        </div>
                    </div>
                    
                    <div class="neon-input-group">
                        <input type="password" 
                               class="neon-input" 
                               name="password" 
                               placeholder="Password" 
                               required>
                        <div class="input-icon">
                            <i class="fas fa-lock"></i>
                        </div>
                    </div>
                    
                    <button type="submit" name="login" class="neon-btn">
                        <i class="fas fa-sign-in-alt"></i>
                        LOGIN
                    </button>
                </form>
            </div>
            
            <!-- Rodapé -->
            <div class="login-footer">
                <a href="https://t.me/eonbry" target="_blank" class="developer-link">
                    <i class="fab fa-telegram"></i>
                    Developer: eonbry _@2026
                </a>
            </div>
        </div>
    </div>
    
    <script src="vendor/jquery/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            // Verificar se há erro de login (mostra diretamente o formulário)
            <?php if (isset($errorMessage)): ?>
                showLoginForm();
            <?php endif; ?>
            
            // Efeito Typewriter para o texto de boas-vindas
            const texts = [
                "Bem-vindo ao IBO Notification System",
                "Sistema de gerenciamento e notificações",
                "Acesso seguro e controlado",
                "Tecnologia e inovação"
            ];
            
            let textIndex = 0;
            let charIndex = 0;
            let isDeleting = false;
            let isWaiting = false;
            const typingSpeed = 50;
            const deletingSpeed = 30;
            const waitTime = 2000;
            
            function typeWriter() {
                const currentText = texts[textIndex];
                const typewriterElement = $('#typewriter');
                
                if (!isDeleting && !isWaiting) {
                    // Digitando
                    if (charIndex < currentText.length) {
                        typewriterElement.text(currentText.substring(0, charIndex + 1));
                        charIndex++;
                        setTimeout(typeWriter, typingSpeed);
                    } else {
                        // Texto completo, esperar
                        isWaiting = true;
                        setTimeout(() => {
                            isWaiting = false;
                            isDeleting = true;
                            setTimeout(typeWriter, 500);
                        }, waitTime);
                    }
                } else if (isDeleting) {
                    // Apagando
                    if (charIndex > 0) {
                        typewriterElement.text(currentText.substring(0, charIndex - 1));
                        charIndex--;
                        setTimeout(typeWriter, deletingSpeed);
                    } else {
                        // Texto apagado, passar para o próximo
                        isDeleting = false;
                        textIndex = (textIndex + 1) % texts.length;
                        setTimeout(typeWriter, 500);
                    }
                }
            }
            
            // Iniciar o efeito typewriter
            setTimeout(typeWriter, 1500);
            
            // Efeito de digitação no subtítulo (nome do sistema)
            let subtitle = "<?php echo addslashes($userName); ?>";
            let typedSubtitle = "";
            let i = 0;
            
            function typeSubtitle() {
                if (i < subtitle.length) {
                    typedSubtitle += subtitle.charAt(i);
                    $('.neon-subtitle').text(typedSubtitle);
                    i++;
                    setTimeout(typeSubtitle, 100);
                }
            }
            
            // Iniciar efeito de digitação no subtítulo
            setTimeout(typeSubtitle, 500);
            
            // Botão Acesso Restrito
            $('#accessBtn').on('click', function() {
                showLoginForm();
            });
            
            function showLoginForm() {
                $('#welcomeText').addClass('animate-out');
                $('#accessBtn').addClass('animate-out');
                
                setTimeout(function() {
                    $('#welcomeText').hide();
                    $('#accessBtn').hide();
                    $('#loginForm').addClass('show');
                    
                    // Foco automático no primeiro input
                    $('input[name="username"]').focus();
                }, 800);
            }
            
            // Efeito de foco nos inputs
            $('.neon-input').on('focus', function() {
                $(this).parent().addClass('focused');
            }).on('blur', function() {
                $(this).parent().removeClass('focused');
            });
            
            // Efeito de loading no botão de login
            $('#loginFormElement').on('submit', function() {
                var btn = $(this).find('.neon-btn');
                if($(this)[0].checkValidity()) {
                    btn.addClass('loading');
                    setTimeout(() => {
                        btn.removeClass('loading');
                    }, 1500);
                }
            });
            
            // Efeito de hover no card
            $('.neon-card').hover(
                function() {
                    $(this).css('transform', 'translateY(-5px)');
                },
                function() {
                    $(this).css('transform', 'translateY(0)');
                }
            );
        });
    </script>
</body>
</html>