<?php
session_start();

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

    if (isset($_SERVER['REMOTE_ADDR'])) {
        $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');
}

// Inicialização de variáveis
$error = "";
$panelLogo = "img/panacilogo.png"; 

// --- CONEXÃO INTERNA (SEM DEPENDER DE ARQUIVOS EXTERNOS) ---
if (!file_exists('api')) { @mkdir('api', 0777, true); }
$db_check1 = new SQLite3("api/database.db");

// Criação da tabela caso não exista
$db_check1->exec("CREATE TABLE IF NOT EXISTS USERS(id INTEGER PRIMARY KEY, NAME TEXT, USERNAME TEXT, PASSWORD TEXT, LOGO TEXT, ADMIN INTEGER, store_type INTEGER)");

// GARANTIA DE ACESSO ADMIN / ADMIN
$checkAdmin = $db_check1->querySingle("SELECT COUNT(*) FROM USERS WHERE USERNAME = 'admin'");
if ($checkAdmin == 0) {
    $db_check1->exec("INSERT INTO USERS(id, NAME, USERNAME, PASSWORD, LOGO, ADMIN, store_type) VALUES(1, 'Administrador', 'admin', 'admin', 'img/logo.png', 1, 1)");
}

// Lógica de Login
if (isset($_POST["login"])) {
    $user_input = $_POST["username"];
    $pass_input = $_POST["password"];

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

    // Validação direta
    if ($user && $pass_input === $user["PASSWORD"]) {
        $_SESSION["admin"] = $user['ADMIN'];
        $_SESSION["N"] = $user["id"];
        $_SESSION["id"] = $user["id"];
        $_SESSION["store_type"] = $user["store_type"];
        $_SESSION['admin_token'] = bin2hex(random_bytes(32));

        header("Location: index.php");
        exit();
    } else {
        $error = "USUÁRIO OU SENHA INCORRETO!";
    }
}

// Busca a Logo no banco (Interno)
$res_logo = $db_check1->querySingle("SELECT LOGO FROM USERS WHERE id=1");
if ($res_logo) {
    $panelLogo = $res_logo;
}

$IPADDRESS = getIPAddress();
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Login • UltraIBO</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
body {
    margin:0;
    font-family: "Segoe UI", sans-serif;
    background: radial-gradient(circle at top, #1b2a45 0%, #050712 60%, #03040a 100%);
    color:white;
    display:flex;
    align-items:center;
    justify-content:center;
    height:100vh;
}

.login-box {
    background: rgba(15,25,45,0.7);
    padding:40px 35px;
    border-radius:18px;
    width: 360px;
    box-shadow: 0 25px 60px rgba(0,0,0,0.7);
    text-align:center;
    border:1px solid rgba(120,170,255,0.2);
}

.logo {
    width:110px;
    height:110px;
    border-radius:14px;
    margin-bottom:14px;
    object-fit:contain;
    background:#0003;
}

.title {
    margin-bottom:6px;
    font-size:22px;
    font-weight:700;
    letter-spacing:0.08em;
}

.subtitle {
    margin-bottom:20px;
    font-size:14px;
    color:#9bb2ff;
}

.input {
    width:93%;
    padding:14px;
    margin-bottom:12px;
    border-radius:12px;
    border:none;
    background:rgba(255,255,255,0.07);
    color:white;
    font-size:14px;
    outline:none;
}

.input:focus {
    box-shadow:0 0 0 2px #66aaff;
}

.btn {
    width:100%;
    padding:14px;
    border-radius:14px;
    background:linear-gradient(135deg,#55c3ff,#2f8dff);
    color:#000;
    font-weight:700;
    letter-spacing:0.1em;
    border:none;
    cursor:pointer;
    box-shadow:0 10px 25px rgba(50,150,255,0.4);
}

.error-box {
    background:rgba(255,80,80,0.2);
    border:1px solid rgba(255,80,80,0.4);
    padding:12px;
    border-radius:10px;
    margin-bottom:14px;
    font-size: 13px;
    color: #ffbaba;
}
</style>
</head>

<body>

<div class="login-box">

    <img src="<?php echo $panelLogo; ?>" class="logo" onerror="this.src='img/panacilogo.png'">

    <div class="title">BEM-VINDO PANACI</div>
    <div class="subtitle">PAINEL DE GERENCIAMENTO</div>

    <?php if (!empty($error)): ?>
        <div class="error-box"><?php echo $error; ?></div>
    <?php endif; ?>

    <form method="post">
        <input type="text" class="input" placeholder="Usuário" name="username" required>
        <input type="password" class="input" placeholder="Senha" name="password" required>
        <button type="submit" class="btn" name="login">ENTRAR</button>
    </form>

   <p style="margin-top:18px;font-size:12px;color:#7c8db8">
    Todos os direitos reservados
    <a href="#" target="_blank" style="color:#7c8db8;text-decoration:none;display:block;margin-top:10px;">
        <img src="https://i.postimg.cc/MTF2WNKB/Picsart-25-12-17-19-18-38-592.png" 
             alt="Tricolor" 
             style="width:14px;height:14px;vertical-align:middle;margin-right:4px;">Panaci Arts</a>
</p>

</div>

</body>
</html>