<?php
session_start();

if (!isset($_SESSION['id']) || !$_SESSION['admin']) {
    echo json_encode(['status' => 'error', 'message' => 'Acesso negado.']);
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST["name"] ?? '');
    $username = trim($_POST["username"] ?? '');
    $password = trim($_POST["password"] ?? '');
    $logo     = $_POST["logo"] ?? '';

    // Verifica se foi enviado um arquivo
    if (isset($_FILES["logo"]) && $_FILES["logo"]["error"] === UPLOAD_ERR_OK) {
        $tmp_name  = $_FILES["logo"]["tmp_name"];
        $file_name = basename($_FILES["logo"]["name"]);
        $upload_dir = "uploads/";
        $upload_path = $upload_dir . $file_name;

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        if (move_uploaded_file($tmp_name, $upload_path)) {
            $logo = $upload_path;
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Erro ao salvar imagem.']);
            exit;
        }
    }

    // Atualiza no banco
    $stmt = $db->prepare("UPDATE USERS SET NAME = :name, USERNAME = :username, PASSWORD = :password, LOGO = :logo WHERE ID = 1");
    $stmt->bindValue(":name", $name, SQLITE3_TEXT);
    $stmt->bindValue(":username", $username, SQLITE3_TEXT);
    $stmt->bindValue(":password", $password, SQLITE3_TEXT); // Você pode aplicar hash aqui se quiser
    $stmt->bindValue(":logo", $logo, SQLITE3_TEXT);

    $result = $stmt->execute();

    if ($result) {
        $_SESSION["name"] = $username;
        echo json_encode([
            'status' => 'ok',
            'logo' => $logo,
            'name' => $name
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Erro ao atualizar.']);
    }

    exit;
}
?>
