<?php

namespace App\Traits;

use Illuminate\Support\Collection;
use Modules\Auth\Entities\User;

trait NotifiesAdmins
{
    /**
     * Get admin users (PENTADBIR and DEVELOPER) who should receive all notifications
     */
    protected function getAdminUsers(): Collection
    {
        return User::whereHas('roles', function ($query) {
            $query->whereIn('name', ['PENTADBIR', 'DEVELOPER']);
        })->get();
    }

    /**
     * Merge admin users with specific role users and return unique collection
     */
    protected function mergeWithAdmins(Collection $specificUsers): Collection
    {
        $adminUsers = $this->getAdminUsers();
        return $specificUsers->merge($adminUsers)->unique('id');
    }

    /**
     * Get users with specific roles and merge with admins
     */
    protected function getUsersWithRolesAndAdmins(array $roles): Collection
    {
        $specificUsers = User::whereHas('roles', function ($query) use ($roles) {
            $query->whereIn('name', $roles);
        })->get();

        return $this->mergeWithAdmins($specificUsers);
    }

    /**
     * Get user IDs from a collection and merge with admin user IDs
     */
    protected function mergeUserIdsWithAdmins($userIds): Collection
    {
        $adminIds = $this->getAdminUsers()->pluck('id');
        
        if ($userIds instanceof Collection) {
            return $userIds->merge($adminIds)->unique()->filter();
        }
        
        return collect($userIds)->merge($adminIds)->unique()->filter();
    }
}

