<?php

class UserPermission {
    public static function getUserHouses($userId) {
        $db = Database::getInstance();
        return $db->fetchAll(
            "SELECT h.* FROM houses h 
             INNER JOIN user_house_permissions uhp ON h.id = uhp.house_id
             WHERE uhp.user_id = ? ORDER BY CAST(h.number AS UNSIGNED)",
            [$userId]
        );
    }

    public static function getUserHouseIds($userId) {
        $db = Database::getInstance();
        $result = $db->fetchAll(
            "SELECT house_id FROM user_house_permissions WHERE user_id = ?",
            [$userId]
        );
        return array_column($result, 'house_id');
    }

    public static function assignHousesToUser($userId, $houseIds) {
        $db = Database::getInstance();
        $db->execute("DELETE FROM user_house_permissions WHERE user_id = ?", [$userId]);

        foreach ($houseIds as $houseId) {
            $db->execute(
                "INSERT INTO user_house_permissions (user_id, house_id) VALUES (?, ?)",
                [$userId, $houseId]
            );
        }
    }

    public static function removeUserFromHouse($userId, $houseId) {
        $db = Database::getInstance();
        return $db->execute(
            "DELETE FROM user_house_permissions WHERE user_id = ? AND house_id = ?",
            [$userId, $houseId]
        );
    }
}
