<?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');
        }
    }

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

session_start();
$jsondata111 = file_get_contents("./includes/ansibo.json");
$json111 = json_decode($jsondata111, true);
$col1 = $json111["info"];
$col2 = $col1["aa"];
$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, ADMIN INTEGER, store_type INTEGER)");

$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, ADMIN, store_type) VALUES('1','Seu Nome','admin','admin','img/logo.png', 1, 1)");
}

$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();
    }


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

    $user = $ret_check->fetchArray();


    if ($user && $_POST["password"] === $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));


        // Redirecionamento alterado para index.php como solicitado
        header("Location: index.php");
        exit();
    } else {
        $message = "<div class=\"alert alert-danger balloon\" id=\"flash-msg\"><h4>USUÁRIO OU SENHA INCORRETO!</h4></div>";
        echo $message;
    }

    $db_check1->close();
}

$date = date("d-m-Y H:i:s");
$IPADDRESS = getIPAddress();

$jsonFilex = './img/panacilogo.png';
$jsonDatax = file_get_contents($jsonFilex);
$imageDatax = json_decode($jsonDatax, true);
$filenamex = $imageDatax[0]['ImageName'];
$uploadmethord = $imageDatax[0]['Upload_type'];

if ($uploadmethord == "by_file") {
    $string = $filenamex;
    $firstLetterRemoved = substr($string, 1);
    $imageFilex = "$firstLetterRemoved";
    $methord = "   Upload Method";
} elseif ($uploadmethord == "by_url") {
    $imageFilex = "$filenamex";
    $methord = "   URL Method";
} else {
    $imageFilex = "https://c4.wallpaperflare.com/wallpaper/159/71/731/errors-minimalism-typography-red-wallpaper-preview.jpg";
    $methord = "";
}
?>



<!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;
}
</style>
</head>

<body>

<div class="login-box">

    <img src="<?php echo (!empty($panelLogo) ? $panelLogo : 'img/panacilogo.png'); ?>" class="logo">

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

    <?php if (!empty($error)): ?>
        <div class="error-box"><?= $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 class="btn" name="login">ENTRAR</button>
    </form>

   <p style="margin-top:18px;font-size:12px;color:#7c8db8">
   
    Todos os direitos reservados
    <a href="CONTATO AQUI" target="_blank" style="color:#7c8db8;text-decoration:none;">
        <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>
