<?php 
session_start();
include 'auth.php';

if (!isset($_SESSION['id'])) {
    header("Location: login.php"); 
    exit(); 
}

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

ini_set("display_errors", 0);
error_reporting(0);

$db = new SQLite3("./api/.anspanel.db");

$stmt = $db->prepare("SELECT * FROM USERS WHERE ID = :id");
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$res = $stmt->execute();
$row = $res->fetchArray();
$message = "";

if (isset($_POST["submit"])) {
    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php");
        exit(); 
    }

    $target_dir = "img2/";
    $target_file = $target_dir . "logo.png";

    if (!empty($_FILES["logo"]["tmp_name"])) {
        move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file);
    }

    $stmt = $db->prepare("UPDATE USERS SET NAME = :name, USERNAME = :username, PASSWORD = :password, LOGO = :logo WHERE ID = :id");
    $stmt->bindValue(':name', htmlspecialchars(trim($_POST["name"])), SQLITE3_TEXT);
    $stmt->bindValue(':username', htmlspecialchars(trim($_POST["username"])), SQLITE3_TEXT);
    $stmt->bindValue(':password', htmlspecialchars(trim($_POST["password"])), SQLITE3_TEXT);
    $stmt->bindValue(':logo', $target_file, SQLITE3_TEXT);
    $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
    
    $result = $stmt->execute();

    if ($result) {
        $_SESSION["name"] = htmlspecialchars(trim($_POST["username"]));
        $_SESSION["logo"] = $target_file . "?t=" . time();
        $message = urlencode("<div class='alert-custom'>DADOS ATUALIZADOS!</div>");
        header("Location: profile.php?m=" . $message);
        exit();
    }
}

$name = $row["NAME"];
$user = $row["USERNAME"];
$pass = $row["PASSWORD"];
$logo = isset($_SESSION["logo"]) ? $_SESSION["logo"] : $row["LOGO"];

include "includes/header.php";
?>

<style>
    /* RESET E CENTRALIZAÇÃO TOTAL */
    .profile-master-container {
        display: flex;
        justify-content: center; /* Centraliza Horizontal */
        align-items: center;     /* Centraliza Vertical */
        width: 100%;
        min-height: 90vh;        /* Garante ocupação da tela */
        padding: 20px;
        box-sizing: border-box;
    }

    .glass-card {
        background: #0f1b34 !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
        border-radius: 25px;
        width: 100%;
        max-width: 450px;       /* Largura ideal Desktop */
        padding: 35px 20px;
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.6);
        box-sizing: border-box;
        margin: auto;           /* Reforço de centralização */
    }

    .title-premium {
        color: #f59e0b !important;
        text-align: center;
        font-weight: 800;
        text-transform: uppercase;
        font-size: 1.25rem;
        margin-bottom: 30px;
        letter-spacing: 1.5px;
    }

    /* AREA DA LOGO CENTRALIZADA */
    .logo-box {
        background: rgba(0, 0, 0, 0.2);
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    .logo-box img {
        max-width: 140px;
        height: auto;
    }

    /* FORMULÁRIO */
    .form-wrapper {
        display: flex;
        flex-direction: column;
        gap: 18px;
        align-items: center;
        width: 100%;
    }

    .input-group-custom {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .label-minimal {
        color: #94a3b8 !important;
        font-size: 0.75rem;
        font-weight: 700;
        text-transform: uppercase;
        margin-bottom: 8px;
    }

    .input-premium {
        width: 100% !important;
        max-width: 360px; /* Garante espaço nas laterais internas do card */
        background: rgba(0, 0, 0, 0.3) !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
        color: #fff !important;
        border-radius: 14px !important;
        padding: 14px !important;
        text-align: center;
        font-size: 0.95rem;
        transition: 0.3s ease;
        box-sizing: border-box;
    }

    .input-premium:focus {
        border-color: #f59e0b !important;
        box-shadow: 0 0 20px rgba(245, 158, 11, 0.15) !important;
        outline: none;
    }

    /* BOTÃO MODERNO CENTRALIZADO */
    .btn-container {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 15px;
    }

    .btn-ultra {
        width: 100%;
        max-width: 360px; /* Alinhado com inputs */
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
        color: #000 !important;
        font-weight: 900 !important;
        text-transform: uppercase;
        border: none !important;
        padding: 16px !important;
        border-radius: 14px !important;
        cursor: pointer;
        box-shadow: 0 8px 20px rgba(245, 158, 11, 0.3);
        transition: 0.4s;
    }

    .btn-ultra:hover {
        transform: translateY(-3px);
        box-shadow: 0 12px 30px rgba(245, 158, 11, 0.5) !important;
    }

    .alert-custom {
        background: rgba(16, 185, 129, 0.15);
        color: #10b981;
        border: 1px solid #10b981;
        padding: 12px;
        border-radius: 15px;
        text-align: center;
        margin-bottom: 20px;
        font-weight: bold;
        width: 100%;
        max-width: 360px;
    }

    /* AJUSTE PARA MOBILE */
    @media (max-width: 480px) {
        .glass-card {
            padding: 30px 15px; /* Menor padding lateral no mobile */
        }
        .input-premium, .btn-ultra, .alert-custom {
            max-width: 100%; /* Ocupa o máximo permitido pelo card no mobile */
        }
    }
</style>

<div class="profile-master-container">
    <div class="glass-card">
        <h2 class="title-premium">Meu Perfil</h2>

        <form method="post" enctype="multipart/form-data" class="form-wrapper">
            <input type="hidden" name="token" value="<?= $_SESSION['admin_token']; ?>">
            
            <?php if (isset($_GET["m"])) echo "<div class='alert-custom'>" . urldecode($_GET["m"]) . "</div>"; ?>

            <div class="logo-box">
                <img src="<?= htmlspecialchars($logo) ?>" alt="Logo">
            </div>

            <div class="input-group-custom">
                <span class="label-minimal">Nome da Empresa</span>
                <input type="text" class="input-premium" name="name" value="<?= htmlspecialchars($name) ?>" required>
            </div>

            <div class="input-group-custom">
                <span class="label-minimal">Usuário</span>
                <input type="text" class="input-premium" name="username" value="<?= htmlspecialchars($user) ?>" required>
            </div>

            <div class="input-group-custom">
                <span class="label-minimal">Senha</span>
                <input type="text" class="input-premium" name="password" value="<?= htmlspecialchars($pass) ?>" required>
            </div>

            <div class="input-group-custom">
                <span class="label-minimal">Nova Logo (.png)</span>
                <input type="file" class="input-premium" name="logo" style="padding-top: 10px !important;">
            </div>

            <div class="btn-container">
                <button type="submit" name="submit" class="btn-ultra">
                    <i class="fas fa-save me-2"></i> Atualizar Perfil
                </button>
            </div>
        </form>
    </div>
</div>

<?php
include "includes/footer.php";
require "includes/ans.php";
?>
</body>
</html>
