<?php
session_start();

if(isset($_GET['update']) && is_numeric($_GET['update'])) {
    $userId = $_GET['update'];
    
    $db = new SQLite3("./api/db/studiolivecode_users.db");
    
    // Use prepared statements to prevent SQL injection
    $stmt = $db->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
    $result = $stmt->execute();
    
    $row = $result->fetchArray(SQLITE3_ASSOC);
    
    if (!$row) {
        die("User not found."); // Handle the case where the user doesn't exist.
    }
    
    if (isset($_POST["submit"])) {
        // Use prepared statements to update user data
        $stmt = $db->prepare("UPDATE users SET name = :name, username = :username, password = :password, logo = :logo, admin = :admin WHERE id = :id");
        $stmt->bindValue(':name', $_POST["name"], SQLITE3_TEXT);
        $stmt->bindValue(':username', $_POST["username"], SQLITE3_TEXT);
        $stmt->bindValue(':password', $_POST["password"], SQLITE3_TEXT);
        $stmt->bindValue(':logo', $_POST["logo"], SQLITE3_TEXT);
        $stmt->bindValue(':admin', $_POST["admin"], SQLITE3_INTEGER);
        $stmt->bindValue(':id', $userId, SQLITE3_INTEGER);
        $stmt->execute();

        header("Location: usuarios.php?r=atualizado");
        exit;
    }

    $name = $row["name"];
    $user = $row["username"];
    $pass = $row["password"];
    $logo = $row["logo"];
    $admin = $row["admin"];
} else {
    die("Invalid user ID."); // Handle invalid user ID.
}
?>

<?php include './includes/header.php'; ?>

<div class="card radius-10">
    <div class="card-body">
        <h4 class="card-title">Editar Perfil</h4>
        <form class="forms-sample" method="post" enctype="multipart/form-data">

            <div class="form-group mb-4">
                <label for="title"><strong>Nome</strong></label>
                <input type="text" class="form-control" placeholder="Digite o Nome" name="name" id="name" value="<?= $name; ?>">
            </div>
            <div class="form-group mb-4">
                <label for="url"><strong>Usuário</strong></label>
                <input type="text" class="form-control" placeholder="Digite o Usuário" name="username" id="username" value="<?= $user; ?>">
            </div>
            <div class="form-group mb-4">
                <label for="url"><strong>Senha</strong></label>
                <input type="text" class="form-control" placeholder="Digite a Senha" name="password" id="password" value="<?= $pass; ?>">
            </div>
            <div class="form-group mb-4">
                <label for="url"><strong>Logo</strong></label>
                <input type="text" class="form-control" placeholder="Digite Link da Logo" name="logo" id="logo" value="<?= $logo; ?>">
            </div>
            <div class="form-group mb-4">
                <label for="url"><strong>Nível Atual: <b style="color: green;"><?= $admin == 1 ? "Admin" : "Usuário"; ?></b></strong></label>
                <select name="admin" class="form-control">
                    <option value="<?= $admin; ?>">Selecione ou deixe branco</option>
                    <option value="1">Admin</option>
                    <option value="0">Usuário</option>
                </select>
            </div>
            <button type="submit" name="submit" class="btn btn-primary mr-2"><i class='bx bx-check mr-1'></i>Editar</button>
        </form>
    </div>
</div>

<?php
if (isset($_GET["r"])) {
    $result = $_GET["r"];
    switch ($result) {
        case "atualizado":
            echo "<script>
            const Toast = Swal.mixin({
              toast: true,
              position: 'bottom',
              showConfirmButton: false,
              timer: 2000,
            })
            Toast.fire({
              icon: 'success',
              title: 'Usuário Atualizado com Sucesso!'
            })</script>";
    }
}
?>

<?php include './includes/footer.php'; ?>