<?php

function getIPAddress()
{
    $ipAddress = 'undefined';

    if (isset($_SERVER)) {
        $ipAddress = $_SERVER['REMOTE_ADDR'];

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ipAddress = $_SERVER['HTTP_CLIENT_IP'];
        }
    } else {
        $ipAddress = getenv('REMOTE_ADDR');

        if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ipAddress = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('HTTP_CLIENT_IP')) {
            $ipAddress = getenv('HTTP_CLIENT_IP');
        }
    }

    return htmlspecialchars($ipAddress, ENT_QUOTES, 'UTF-8');
}

session_start();
$jsondata111 = file_get_contents("./includes/ansibo.json");
$json111 = json_decode($jsondata111, true);
$col1 = $json111["info"];
$col2 = $col1["aa"];

// Conexão com o banco de dados SQLite
$db_check1 = new SQLite3("api/.anspanel.db");
$db_check1->exec("CREATE TABLE IF NOT EXISTS USERS(id INT PRIMARY KEY, NAME TEXT, USERNAME TEXT, PASSWORD TEXT, LOGO TEXT)");

// Inicializa o banco de dados com um usuário padrão se estiver vazio
$rows = $db_check1->query("SELECT COUNT(*) as count FROM USERS");
$row = $rows->fetchArray();
$numRows = $row["count"];

if ($numRows == 0) {
    $db_check1->exec("INSERT INTO USERS(id, NAME, USERNAME, PASSWORD, LOGO) VALUES('1','Seu Nome','admin','admin','img2/logo.png')");
}

// Carrega informações do usuário
$res_login = $db_check1->query("SELECT * FROM USERS WHERE id='1'");
$row_login = $res_login->fetchArray();
$name_login = $row_login["NAME"];
$logo_login = $row_login["LOGO"];

if (isset($_POST["login"])) {
    if (!$db_check1) {
        echo $db_check1->lastErrorMsg();
    }

    // Usando prepared statement para evitar injeção de SQL
    $username = $_POST["username"];
    $password = $_POST["password"];
    
    $stmt = $db_check1->prepare("SELECT * FROM USERS WHERE USERNAME = :username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    $user = $result->fetchArray(SQLITE3_ASSOC);

    // Verifica se o usuário existe e se a senha está correta
    if ($user && $password === $user['PASSWORD']) { // Verifica se a senha em texto claro
        $_SESSION["admin"] = $user['ADMIN']; // Supondo que você tenha um campo 'ADMIN'
        $_SESSION["N"] = $user["id"];
        $_SESSION["id"] = $user["id"];
        $_SESSION["store_type"] = $user["store_type"];

        $path = "users";
        if ($user["store_type"] == '2') {
            $path .= '_mac';
        }

        header("Location: $path.php");
        exit();
    } else {
        $message = "<div class=\"alert alert-danger\" id=\"flash-msg\"><h4><i class=\"icon fa fa-times\"></i>Usuário ou senha inválidos!</h4></div>";
        echo $message;
    }

    $db_check1->close();
}

$date = date("d-m-Y H:i:s");
$IPADDRESS = getIPAddress();
$imageFilex = '/img2/logo.png?' . time();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PAINEL IBO REVENDA</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" crossorigin="anonymous" />
    <link href="css/sb-admin-<?php echo $col2; ?>.css" rel="stylesheet">
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <style>
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #f8f9fc; /* Cor de fundo mais clara */
        }
        .container {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            height: 100vh;
        }
        .form-container {
            background-color: rgba(255, 255, 255, 0.9); /* Fundo branco com leve transparência */
            padding: 20px;
            border-radius: 10px;
            border-top: 5px solid #4e73df;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            margin-top: 20px;
            max-width: 400px;
            width: 100%;
        }
        .image-container {
            display: flex;
            justify-content: center; /* Centraliza a imagem */
            margin-bottom: 20px; /* Margem inferior da imagem */
        }
        .outside-image {
            width: 50%; /* Largura da imagem */
            max-width: 100%;
            height: auto; /* Mantém a proporção da imagem */
        }
        .form-title {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
        }
    </style>
</head>
<body class="bg-gradient-primary">
    <div class="container">
        <div class="form-container">
            <div class="image-container">
                <img src="<?= $imageFilex ?>" alt="Descrição da Imagem" class="img-fluid outside-image">
            </div>
            <div class="form-title">PAINEL IBO REVENDAS</div>
            <form method="POST">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="NOME DE USUÁRIO" name="username" required autofocus />
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <input type="password" class="form-control" placeholder="SENHA" name="password" required />
                        <button type="button" class="btn btn-secondary password-toggle-icon" onclick="togglePasswordVisibility()">
                            <i class="fas fa-eye-slash"></i>
                        </button>
                    </div>
                </div>
                <div class="form-group">
                    <button class="btn btn-primary btn-lg btn-block" name="login" type="submit">ENTRAR</button>
                </div>
                <br>
    <a href="seuapp/Ibo-09-Temas-Rev.apk" class="btn btn-lg btn btn-primary btn-block">Baixar App</a>
</div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePasswordVisibility() {
            const passwordInput = document.querySelector('[name="password"]');
            const passwordIcon = document.querySelector('.password-toggle-icon i');

            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                passwordIcon.className = 'fas fa-eye';
            } else {
                passwordInput.type = 'password';
                passwordIcon.className = 'fas fa-eye-slash';
            }
        }

        // Oculta a mensagem de erro após 2 segundos
        setTimeout(function() {
            var flashMsg = document.getElementById('flash-msg');
            if (flashMsg) {
                flashMsg.style.opacity = '0';
                setTimeout(function() {
                    flashMsg.style.display = 'none';
                }, 500);
            }
        }, 2000);
    </script>
</body>
</html>