<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_SSO_Provider_Microsoft extends AIEO_SSO_Provider_Base {

    const AUTH_URL    = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
    const TOKEN_URL   = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
    const PROFILE_URL = 'https://graph.microsoft.com/v1.0/me?$select=id,givenName,surname,displayName,mail,userPrincipalName';

    public function code()  { return 'microsoft'; }
    public function label() { return 'Microsoft'; }

    public function auth_url($state, $redirect_uri) {
        $cfg = $this->credentials();
        if ($cfg['client_id'] === '') {
            return new WP_Error('sso_no_client_id', 'Microsoft client_id missing.');
        }
        return self::AUTH_URL . '?' . http_build_query(array(
            'response_type' => 'code',
            'client_id'     => $cfg['client_id'],
            'redirect_uri'  => $redirect_uri,
            'response_mode' => 'query',
            'scope'         => 'openid profile email offline_access User.Read',
            'state'         => $state,
        ));
    }

    public function exchange_token($code, $redirect_uri) {
        $cfg = $this->credentials();
        return $this->http_post_form(self::TOKEN_URL, array(
            'grant_type'    => 'authorization_code',
            'code'          => $code,
            'redirect_uri'  => $redirect_uri,
            'client_id'     => $cfg['client_id'],
            'client_secret' => $cfg['client_secret'],
            'scope'         => 'openid profile email User.Read',
        ));
    }

    public function fetch_profile(array $token) {
        $access = (string) ($token['access_token'] ?? '');
        if ($access === '') { return new WP_Error('sso_no_token', 'Microsoft did not return an access_token.'); }
        $resp = $this->http_get_authorised(self::PROFILE_URL, $access);
        if (is_wp_error($resp)) { return $resp; }

        $email = (string) ($resp['mail'] ?? '');
        if ($email === '') { $email = (string) ($resp['userPrincipalName'] ?? ''); }
        $first = (string) ($resp['givenName'] ?? '');
        $last  = (string) ($resp['surname']   ?? '');
        if ($first === '' && $last === '' && !empty($resp['displayName'])) {
            list($first, $last) = $this->split_name((string) $resp['displayName']);
        }

        return array(
            'provider_uid' => (string) ($resp['id'] ?? ''),
            'email'        => $email,
            'first_name'   => $first,
            'last_name'    => $last,
            'avatar'       => '', 
            'raw'          => $resp,
        );
    }
}

add_filter('aieo_sso_providers', static function (array $providers) {
    if (!isset($providers['microsoft']) && class_exists('AIEO_SSO_Provider_Microsoft')) {
        $providers['microsoft'] = new AIEO_SSO_Provider_Microsoft();
    }
    return $providers;
});
