<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

$dircheck = substr($_SERVER["REQUEST_URI"], 0, strrpos($_SERVER["REQUEST_URI"], "/"));
$dircheck2 = substr($dircheck, 1);
$postu = $_POST["username"] . $dircheck2;

// Verifica se o usuário já está logado e redireciona para a página de usuários
if (isset($_SESSION[$dircheck2]) && $_SESSION[$dircheck2] == $dircheck2) {
    header("location: dashboard.php");
    exit;
}

function getRealIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

try {
    $db = new SQLite3("./api/db/studiolivecode_users.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$db->exec("CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, name VARCHAR(100), username VARCHAR(100), password VARCHAR(100), logo VARCHAR(100), nivel VARCHAR(100), admin VARCHAR(100), store_type VARCHAR(100), mac_amount VARCHAR(100))");

$rows = $db->querySingle("SELECT COUNT(*) as count FROM users");
if ($rows == 0) {
    $db->exec("INSERT INTO users(name, username, password, logo, nivel, admin, store_type, mac_amount) 
        VALUES('Admin', 'admin', 'admin', 'img/logo.png', '0', '1', NULL, NULL)");
    $db->exec("INSERT INTO users(name, username, password, logo, nivel, admin, store_type, mac_amount) 
        VALUES('StudioLiveCode', 'crocko', '10203040', 'img/logo.png', '1', '1', NULL, NULL)");
}

$ip = getRealIP();

// Tratamento de erros ao obter informações do IP
$details = @file_get_contents("https://ipinfo.io/$ip/json");
if ($details === false) {
    // Se houver erro, defina informações padrão ou trate conforme necessário
    $country = "Unknown";
    $state = "Unknown";
    $isp = "Unknown";
} else {
    $details = json_decode($details);
    $country = $details->country ?? "Unknown";
    $state = $details->region ?? "Unknown";
    $isp = preg_replace("/AS\\d{1,}\\s/", "", $details->org ?? "Unknown");
}

$date = date("d/m/Y H:i:s");
$IPADDRESS = $ip;

try {
    $dbs = new SQLite3("./api/db/studiolivecode_snoop.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$dbs->exec("CREATE TABLE IF NOT EXISTS logs(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, date TEXT, access TEXT, state TEXT, country TEXT, isp TEXT, ipaddress TEXT)");

if (isset($_POST["login"])) {
    $username = $_POST["username"];
    $password = $_POST["password"];

    $stmt = $db->prepare("SELECT id, password, admin, username FROM users WHERE username = :username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();

    $row = $result->fetchArray(SQLITE3_ASSOC);
    if ($row) {
        $id_check = $row["id"];
        $isAdmin = $row['admin'];
        $username_check = $row['username'];

        if ($password === $row["password"]) {
            $_SESSION["studiolivecodevu"] = true;
            $_SESSION["id"] = $id_check;
            $_SESSION[$postu] = $postu;
            $_SESSION[$dircheck2] = $dircheck2;
            $_SESSION["U"] = $username_check;

            $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
            VALUES(:date, 'Enter Admin', :state, :country, :isp, :IPADDRESS)");
            $stmt->bindValue(':date', $date, SQLITE3_TEXT);
            $stmt->bindValue(':state', $state, SQLITE3_TEXT);
            $stmt->bindValue(':country', $country, SQLITE3_TEXT);
            $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
            $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
            $stmt->execute();
            header("Location: dashboard.php");
            exit();
        } else {
            $message = "<div class=\"alert alert-danger\" id=\"flash-msg\"><h4><i class=\"icon fa fa-times\"></i>Senha Errada!</h4></div>";
            $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
                VALUES(:date, 'Senha Inválida', :state, :country, :isp, :IPADDRESS)");
            $stmt->bindValue(':date', $date, SQLITE3_TEXT);
            $stmt->bindValue(':state', $state, SQLITE3_TEXT);
            $stmt->bindValue(':country', $country, SQLITE3_TEXT);
            $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
            $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
            $stmt->execute();
            echo $message;
        }
    } else {
        $message = "<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>";
        $stmt = $dbs->prepare("INSERT INTO logs(date, access, state, country, isp, ipaddress) 
            VALUES(:date, 'Usuário Inválido', :state, :country, :isp, :IPADDRESS)");
        $stmt->bindValue(':date', $date, SQLITE3_TEXT);
        $stmt->bindValue(':state', $state, SQLITE3_TEXT);
        $stmt->bindValue(':country', $country, SQLITE3_TEXT);
        $stmt->bindValue(':isp', $isp, SQLITE3_TEXT);
        $stmt->bindValue(':IPADDRESS', $IPADDRESS, SQLITE3_TEXT);
        $stmt->execute();
        echo $message;
    }

    $db->close();
    $dbs->close();
}

try {
    $dbc = new SQLite3("./api/db/studiolivecode_bot.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$dbc->exec("CREATE TABLE IF NOT EXISTS bot(id INTEGER PRIMARY KEY  AUTOINCREMENT, bot_url TEXT, bot_dns TEXT, bot_status TEXT, bot_name TEXT)");
$res = $dbc->query("SELECT COUNT(*) as count FROM bot");
if ($res) { // Verifica se a consulta foi bem-sucedida
    $rowc = $res->fetchArray();
    $numRowsc = $rowc["count"];
} else {
    // Tratar o caso em que a consulta falhou
    echo "Erro ao realizar a consulta ao banco de dados bot.";
}
if ($numRowsc == 0) {
    $dbc->exec("INSERT INTO bot(id, bot_url, bot_dns, bot_status, bot_name) VALUES('1', '', '', '0', 'StudioLiveCode IBO')");
}

try {
    $db3 = new SQLite3("./api/db/studiolivecode_imagens.db");
} catch (Exception $e) {
    die('Unable to open database: ' . $e->getMessage());
}

$db3->exec('CREATE TABLE IF NOT EXISTS bg(id INT PRIMARY KEY NOT NULL, path TEXT)');
$rows = $db3->query('SELECT COUNT(*) as count FROM bg');
$numRows = $rows->fetchArray(SQLITE3_ASSOC);
if ($numRows['count'] == 0) {
    $queries = [
        "INSERT INTO bg(id, path) VALUES('1', '')"
    ];

    foreach ($queries as $query) {
        $db3->exec($query);
    }
}

$db3->exec("CREATE TABLE IF NOT EXISTS logo(id INT PRIMARY KEY NOT NULL, path TEXT)");
$rows = $db3->query('SELECT COUNT(*) as count FROM logo');
$numRows = $rows->fetchArray(SQLITE3_ASSOC);
if ($numRows['count'] == 0) {
    $queries = [
        "INSERT INTO logo(id, path) VALUES('1', '')"
    ];

    foreach ($queries as $query) {
        $db3->exec($query);
    }
}

$resk = $db3->query("SELECT * FROM logo WHERE id='1'");
$rowk = $resk->fetchArray();
$logo = $rowk["path"];
$db3->close();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="author" content="STUDIOLIVECODE">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <title>StudioLiveCode Vu Pro Manager</title>
    <meta content="./assets/images/logo.png" property="og:image"/>
    <style>
        body {
            background-color: #181828;
            background-image: url("./assets/images/default_background.jpg");
            color: #fff;
        }

        #particles-js {
            background-size: cover;
            background-position: 50% 50%;
            background-repeat: no-repeat;
            background: #8000FF;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .particles-js-canvas-el {
            position: fixed;
        }

        .login-form {
            background-color: rgba(0, 0, 0, 0.7); /* Cor de fundo com transparência */
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0px 0px 20px rgba(255, 255, 255, 0.2);
            border-top: 5px solid #0A38D1;
        }

        .login-form img {
            width: 75%;
            margin: 0 auto;
            display: block;
            margin-bottom: 20px;
        }

        .login-form input[type="text"],
        .login-form input[type="password"] {
            background-color: #333;
            color: #fff;
        }

        .login-form input[type="submit"] {
            background-color: #0A38D1;
            border: none;
        }

        .login-form input[type="submit"]:hover {
            background-color: #0529a3;
        }
    </style>
</head>
<body>
<div id="js-particles"></div>
<br><br>
<div class="container">
    <div class="row">
        <div class="col-lg-4 mx-md-auto">
            <form method="post" class="login-form">
                <img src="<?php
                if (empty($rowk['path'])) {
                    echo 'assets/images/logo1.png';
                } else {
                    echo $rowk['path'];
                } ?>" alt="">
                
                <div class="form-group">
                    <input type="text" class="form-control form-control-lg"
                           placeholder="Usuário" name="username" required autofocus>
                </div>
                <div class="form-group">
                    <input type="password" class="form-control form-control-lg"
                           placeholder="Senha" name="password" required>
                </div>
                <input type="submit" class="btn btn-primary btn-lg btn-block" value="Entrar" name="login">
                <center style="margin-top: 20px;"><a class="list-grup-item" href="https://topnettv.top" target="_blank">&nbsp&nbsp&nbsp&nbsp&#169  <?php echo date("Y")?> * TOPNET TV * </a></center>
            </form>
            
        </div>
    </div>
</div>
<br><br>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
<!--<script src="https://cdn.jsdelivr.net/particles.js/2.0.0/particles.min.js"></script>-->
<!--<script src="assets/js/particles.js"></script>-->
</body>
</html>