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

// 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);
       // $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_iboPlayer2'] = true;
        $_SESSION['seller_name'] = $usuario;
        $_SESSION['aviso_seller'] = false;
        $_SESSION['id'] = $revendaId;
        header('Location: revenda/index.php');
    } else {
         LoginReseller($usernamee, $password);
        //$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();
}

// 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);
        //$errorMessage = '<div class="alert alert-danger" id="flash-msg"><h4><i class="icon fa fa-times"></i>Not a Valid User!</h4></div>';
        //echo $errorMessage;
    } 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);
        //$errorMessage = '<div class="alert alert-danger" id="flash-msg"><h4><i class="icon fa fa-times"></i>Wrong Password!</h4></div>';
        //echo $errorMessage;
    }

    $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>
<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>Maxloja Aplicativos</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">
</head>
<body class="bg-gradient-primary">
    <div class="container">
        <div class="row justify-content-center">
            <center>
                <body>
                    <div class="wrapper">
                        <br><br><br>
                        <div class="container" style="margin-top:30px;">
                            <div style="width:400px; margin:0 auto;">
                                <div class="row">
                                    <div class="center">
                                        <center><img src="<?php echo $userLogo; ?>" width="180" height="100" class="center" alt=""></center>
                                        <br>
                                        <h3 class="text-center text-light"><strong>Maxloja Aplicativos</strong></h3>
                                        <h3 class="text-center text-light"><?php echo $userName; ?></h3>
                                        <h5 class="text-center text-light">Bem Vindo</h5>
                                        <br>
                                        <div>
                                            <div style="width:400px; margin:0 auto;">
                                                <form method="post">
                                                    <input type="text" class="form-control text-primary" placeholder="Username" name="username" required autofocus><br>
                                                    <input type="password" class="form-control text-primary" placeholder="Password" name="password" required><br>
                                                    <button class="btn btn-lg btn btn-primary btn-block" name="login" type="submit">LOGIN</button>
                                                </form>
                                            </div>
                                        </div>
                                        <div class="card-body">
                                            <div class="panel-body">
                                                <p class="text-center text-warning">Hora de chegada: "<i><?php echo date('d-m-Y H:i:s'); ?></i>"</p>
                                                <p class="text-center text-warning">Endereço de IP: "<i><?php echo getIPAddress(); ?></i>"</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </body>
            </center>
        </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>