<?php

class GroupModel
{
    public static function getAllGroups()
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        $sql = "SELECT group_id, group_name FROM user_groups ORDER BY group_id";
        $query = $database->prepare($sql);
        $query->execute();
        return $query->fetchAll();
    }

    public static function getGroupNameById($group_id)
    {
        $database = DatabaseFactory::getFactory()->getConnection();
        $sql = "SELECT group_name FROM user_groups WHERE group_id = :gid LIMIT 1";
        $query = $database->prepare($sql);
        $query->execute(array(':gid' => $group_id));
        $row = $query->fetch();
        return $row ? $row->group_name : null;
    }

    public static function setUserGroup($userId, $groupId)
    {
        if (!is_numeric($userId) || !is_numeric($groupId)) {
            return false;
        }

        // Do not allow changing own group via admin UI to prevent lockout
        if ((int)$userId === (int)Session::get('user_id')) {
            Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_CANT_DELETE_SUSPEND_OWN'));
            return false;
        }

        // Only allow groups that exist in lookup
        $database = DatabaseFactory::getFactory()->getConnection();
        $check = $database->prepare("SELECT 1 FROM user_groups WHERE group_id = :gid LIMIT 1");
        $check->execute([':gid' => $groupId]);
        if ($check->rowCount() !== 1) {
            return false;
        }

        $query = $database->prepare("UPDATE users SET user_account_type = :gid WHERE user_id = :uid LIMIT 1");
        $query->execute([':gid' => $groupId, ':uid' => $userId]);

        if ($query->rowCount() === 1) {
            Session::add('feedback_positive', 'Benutzergruppe aktualisiert.');
            return true;
        }

        return false;
    }
}
