<?php

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();

// Código do downloader a ser copiado (edite aqui)
$codigoDownloader = "11968882649"; // Altere para o código desejado

// 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="alert alert-danger" id="flash-msg"><h4><i class="icon fa fa-times"></i>Não é um usuário válido!</h4></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="alert alert-danger" id="flash-msg"><h4><i class="icon fa fa-times"></i>Senha incorreta!</h4></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['N'] = $userId;
        $_SESSION['admin_name'] = $username;
        $_SESSION['id'] = $userId;
        header('Location: users.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 MASTER - Login</title>
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Nunito:200,300,400,600,700,800,900" rel="stylesheet">
    <link rel="shortcut icon" href="favicon1.ico" type="image/x-icon">
    <link rel="stylesheet" href="css/style.css">
    <style>
        body {
            background: url('img/body_backgroud_login.png') no-repeat center center fixed;
            background-size: cover;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            font-family: 'Nunito', sans-serif;
        }
        .login-container {
            background: rgba(0, 0, 0, 0.5);
            padding: 30px;
            border-radius: 10px;
            text-align: center;
            color: white;
            max-width: 400px;
            width: 100%;
        }
        .login-container img {
            width: 180px;
            height: auto;
        }
        .login-container h3, .login-container h5 {
            margin: 10px 0;
        }
        .form-control {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border: none;
            border-radius: 5px;
        }
        .btn {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 5px;
            background: #007bff;
            color: white;
            font-size: 16px;
            cursor: pointer;
        }
        .btn:hover {
            background: #0056b3;
        }
        .info-link {
            color: #ffcc00;
            text-decoration: none;
        }

        /* Estilos para o botão de copiar código */
        .btn-downloader {
            background-color: #ff7700;
            border-color: #ff6600;
            color: white;
            margin-top: 10px;
        }
        .btn-downloader:hover {
            background-color: #e66900;
            border-color: #cc5c00;
            color: white;
        }
        .btn-block {
            display: block;
            width: 100%;
        }
        .mt-2 {
            margin-top: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <img src="<?php echo $userLogo; ?>" alt="Logo">
        <h3><strong>IBO MASTER</strong></h3>
        <h3><?php echo $userName; ?></h3>
        <h5>Bem Vindo</h5>
        <form method="post">
            <input type="text" class="form-control" placeholder="Nome de usuário" name="username" required autofocus>
            <input type="password" class="form-control" placeholder="Senha" name="password" required>
            <button class="btn" name="login" type="submit">ACESSAR</button>
        </form>
        <br>
        <!-- Substituído o botão "Baixar App" pelo botão de copiar código -->
        <button type="button" class="btn btn-downloader btn-block" id="copyDownloaderBtn">
            <i class="fas fa-copy"></i> Copiar Código DOWNLOADER
        </button>
        <br><br>
        <p>Informações: <a href="https://globallweb.com.br/" target="_blank" class="info-link">GLOBAL WEB</a></p>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            var copyBtn = document.getElementById('copyDownloaderBtn');
            if (copyBtn) {
                copyBtn.addEventListener('click', function() {
                    var codigoDownloader = "<?php echo $codigoDownloader; ?>";
                    
                    // Método alternativo para copiar usando textarea temporário
                    var tempInput = document.createElement("input");
                    tempInput.value = codigoDownloader;
                    document.body.appendChild(tempInput);
                    tempInput.select();
                    document.execCommand("copy");
                    document.body.removeChild(tempInput);
                    
                    // Feedback visual
                    var originalText = this.innerHTML;
                    this.innerHTML = '<i class="fas fa-check"></i> Código Copiado!';
                    this.classList.add('btn-success');
                    this.classList.remove('btn-downloader');
                    
                    setTimeout(function() {
                        var btn = document.getElementById('copyDownloaderBtn');
                        btn.innerHTML = originalText;
                        btn.classList.add('btn-downloader');
                        btn.classList.remove('btn-success');
                    }, 2000);
                });
            }
        });
    </script>
</body>
</html>