<?php

namespace classes;

require_once WD . '/modules/entra/entra_c.php';

use entra\entra_c;
use Microsoft\Graph\GraphServiceClient;
use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContext;
use Microsoft\Kiota\Authentication\Oauth\ClientCredentialContextBuilder;


class entra
{
    /**
     * Configuration of the Entra module
     * @var entra_c
     */
    public entra_c $config;

    public function __construct()
    {
        $this->config = new entra_c();
    }

    public function get_users($array = false): array|object
    {
        $graphClient = $this->getGraphClient();

        $users = $graphClient->users()
            ->get()
            ->wait()
            ->getValue();
        if (!$array) {
            return $users;
        }
        $result = [];
        foreach ( $users as $user ) {
            $result[] = [
                'id' => $user->getId(),
                'displayName' => $user->getDisplayName(),
                'mail' => $user->getMail(),
                'userPrincipalName' => $user->getUserPrincipalName(),
            ];
        }
        return $result;
    }

    public function getGraphClient(): GraphServiceClient
    {
        return new GraphServiceClient(
            $this->getTokenRequestContext(),
        );
    }

    public function getTokenRequestContext(): ClientCredentialContext
    {
        return new ClientCredentialContext(
            $this->config->tenant_id->getVariableValue(),
            $this->config->client_id->getVariableValue(),
            $this->config->client_secret->getVariableValue()
        );
    }
}