<?php
// Funções para obter IP, login, e manipulação do banco de dados
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\', \'maxrebrands29\', \'maxrebrands29\', \'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 http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LDS Ultra Ibo</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,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
    <link href="css/sb-admin-<?php echo $aa; ?>.css" rel="stylesheet">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <style>
        body {
            background: linear-gradient(to right, #6a11cb, #2575fc);
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }

        .container {
            display: flex;
            justify-content: center;
            align-items: center;
            max-width: 900px;
            width: 100%;
        }

        .left-image {
            display: none;
            flex: 1;
            padding-right: 20px;
            animation: float 3s ease-in-out infinite;
        }

        /* Adicionando movimento flutuante */
        @keyframes float {
            0%, 100% {
                transform: translateY(0);
            }
            50% {
                transform: translateY(-10px);
            }
        }

        .login-container {
            background: rgba(0, 0, 0, 0.7);
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
            flex: 1;
            max-width: 500px;
            text-align: center;
        }

        .login-container img {
            max-width: 180px;
        }

        .login-container h3, .login-container h5 {
            color: #fff;
        }

        .form-control {
            margin-bottom: 10px;
        }

        .btn-primary {
            width: 100%;
        }

        .btn-secondary {
            width: 100%;
            background-color: #008CBA;
            border-color: #008CBA;
        }

        @media (min-width: 768px) {
            .left-image {
                display: block;
            }
            .login-container {
                flex: 2;
                margin-left: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="left-image">
            <img src="https://i.postimg.cc/90YcDRV2/httpsarquivos-scriptphpbrasil-com-bruploads-Loja-de-Aplicativo2-0-zip.png" alt="Imagem de exemplo" style="width: 100%; height: auto;">
        </div>

        <div class="login-container">
            <img src="<?php echo $userLogo; ?>" alt="Logo">
            <h3 class="text-center"><strong></strong></h3>
            <h3 class="text-center"><?php echo $userName; ?></h3>
            <h5 class="text-center">Bem Vindo</h5>
            <form method="post">
                <input type="text" class="form-control text-primary" placeholder="Nome de usuário" name="username" required autofocus><br>
                <input type="password" class="form-control text-primary" placeholder="Senha" name="password" required><br>
                <button class="btn btn-lg btn-primary btn-block" name="login" type="submit">ENTRAR</button><br>
                <button class="btn btn-lg btn-secondary btn-block" type="button" onclick="window.location.href='apkaqui/foxstreaming.apk'">BAIXAR APLICATIVO</button>
            </form>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
</body>
</html>
