<!-- BR APPS PROJETOS -->
<?php
ini_set("display_errors", 0);
ini_set("display_startup_errors", 0);
error_reporting(E_ALL);

session_start();

// Ler configuração
$configPath = "./includes/ansibo.json";
$jsondata111 = file_exists($configPath) ? file_get_contents($configPath) : '{}';
$json111 = json_decode($jsondata111, true);
$col1 = $json111["info"] ?? [];
$col2 = $col1["aa"] ?? "default";

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

// Criar usuários padrão se não existir
$numRows = $db_check1->querySingle("SELECT COUNT(*) FROM USERS");
if ($numRows == 0) {
    $db_check1->exec("INSERT INTO USERS(id, NAME, USERNAME, PASSWORD, LOGO, CORP) VALUES
        (1, 'Your Name', 'admin', 'admin', 'img/logo.png', 'img/corp.png')");
    $db_check1->exec("INSERT INTO USERS(id, NAME, USERNAME, PASSWORD, LOGO, CORP) VALUES
        (2, 'ANS MASTER ADMIN', 'APPSNSCRIPTSADMIN', 'APPSNSCRIPTSADMIN', 'img/admin.png', 'img/corp.png')");
}

// Carregar dados do primeiro usuário
$row_login = $db_check1->querySingle("SELECT * FROM USERS WHERE id=1", true);
$name_login = $row_login['NAME'] ?? 'User';
$logo_login = $row_login['LOGO'] ?? 'img/logo.png';
$corp_login = $row_login['CORP'] ?? 'img/corp.png';

// Processar login
if (isset($_POST['login'])) {
    $username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');
    $password = $_POST['password'] ?? '';

    $stmt = $db_check1->prepare("SELECT * FROM USERS WHERE USERNAME = :username LIMIT 1");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $user = $stmt->execute()->fetchArray(SQLITE3_ASSOC);

    if (!$user) {
        echo "<div class='alert alert-danger'><h4><i class='icon fa fa-times'></i> Not a Valid User!</h4></div>";
    } elseif ($user['PASSWORD'] === $password) {
        $_SESSION['ansnscript_admin'] = true;
        $_SESSION['N'] = $user['id'];
        $_SESSION['id'] = $user['id'];

        $redirect = ($username === 'admin' || $password === 'admin') ? 'hello.php' : 'users.php';
        header("Location: $redirect");
        exit();
    } else {
        echo "<div class='alert alert-danger'><h4><i class='icon fa fa-times'></i> Wrong Password!</h4></div>";
    }
    $db_check1->close();
}

// Registrar log de acesso
$IPADDRESS = real_ip();
$date = date("d-m-Y H:i:s");
$db_logs = new SQLite3("./api/.logs.db");
$db_logs->exec("
    CREATE TABLE IF NOT EXISTS logs(
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        date TEXT,
        ipaddress TEXT
    )
");
$db_logs->exec("INSERT INTO logs(date, ipaddress) VALUES('$date', '$IPADDRESS')");

// Função para pegar IP real
require_once "includes/ans.php";
function real_ip() {
    foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) return htmlspecialchars($_SERVER[$key], ENT_QUOTES, 'UTF-8');
    }
    return 'undefined';
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>UniTV BETA V1</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
<style>
body {
    font-family:'Inter',sans-serif;
    min-height:100vh;
    display:flex;
    align-items:center;
    justify-content:center;
    margin:0;
    background: linear-gradient(135deg,#89f7fe,#66a6ff,#c3cfe2,#89f7fe);
    background-size: 800% 800%;
    animation: gradientAnimation 20s ease infinite;
    color:#222831;
}
@keyframes gradientAnimation {0%{background-position:0% 50%;}50%{background-position:100% 50%;}100%{background-position:0% 50%;}}

.form-container {
    background:#fff;
    padding:3rem;
    border-radius:1.8rem;
    box-shadow:0 20px 30px rgba(0,0,0,0.15),0 8px 16px rgba(102,166,255,0.25);
    width:100%;
    max-width:420px;
}
.brand {
    text-align:center;
    margin-bottom:2rem;
    font-weight:700;
    font-size:2rem;
    color:#3f51b5;
    letter-spacing:1.5px;
}
input.form-control {
    border-radius:1rem;
    border:1.6px solid #a8b2ff;
    padding:0.85rem 1.2rem;
    font-size:1.1rem;
    background:#f8fbff;
    color:#2c3e50;
}
input.form-control:focus {border-color:#3f51b5;box-shadow:0 0 12px rgba(63,81,181,0.5);outline:none;background:#fff;}
.btn-primary {
    background:linear-gradient(45deg,#536dfe,#8e99f3);
    border:none;
    border-radius:2rem;
    font-weight:700;
    padding:0.85rem 0;
    box-shadow:0 10px 25px rgba(83,109,254,0.6);
    width:100%;
}
.btn-primary:hover {background:linear-gradient(45deg,#3f51b5,#5c6bc0);box-shadow:0 14px 40px rgba(63,81,181,0.8),0 0 8px rgba(63,81,181,0.5);}
.alert {border-radius:1rem;padding:0.9rem 1.2rem;font-weight:600;margin-bottom:1rem;}
.alert-danger {background:#ffdddd;color:#b02a37;border:1.5px solid #b02a37;}
</style>
</head>
<body>
<div class="form-container">
    <div class="brand">UniTV BETA V1</div>
    <?php if ($message) echo $message; ?>
    <form method="POST" autocomplete="off">
        <div class="mb-3">
            <input type="text" name="username" class="form-control" placeholder="NOME DE USUÁRIO" required autofocus>
        </div>
        <div class="mb-3">
            <input type="password" name="password" class="form-control" placeholder="SENHA" required>
        </div>
        <button type="submit" name="login" class="btn btn-primary mb-2">Login</button>
        <p class="text-center text-muted small"><?php echo htmlspecialchars($date); ?></p>
    </form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
