<?php
/**
 * Microsoft OAuth Token Provider for PHPMailer.
 *
 * @package NimblyMail\SMTP
 */

namespace NimblyMail\SMTP\Mailers;

use PHPMailer\PHPMailer\OAuthTokenProvider;

defined( 'ABSPATH' ) || exit;

/**
 * Class MicrosoftOAuthTokenProvider
 *
 * Minimal OAuthTokenProvider implementation that hands a pre-refreshed
 * Microsoft Identity Platform access token to PHPMailer's XOAUTH2
 * authentication. Microsoft's SMTP endpoint at smtp.office365.com:587
 * accepts the same XOAUTH2 SASL string format Google uses, so this class
 * mirrors GoogleOAuthTokenProvider one-for-one.
 *
 * @since 1.0.0
 */
class MicrosoftOAuthTokenProvider implements OAuthTokenProvider {

    /**
     * The user's email address (Microsoft account UPN / email).
     *
     * @since 1.0.0
     *
     * @var string
     */
    private string $email;

    /**
     * The OAuth2 access token.
     *
     * @since 1.0.0
     *
     * @var string
     */
    private string $access_token;

    /**
     * Constructor.
     *
     * @since 1.0.0
     *
     * @param string $email        The user's email address.
     * @param string $access_token The OAuth2 access token.
     */
    public function __construct( string $email, string $access_token ) {
        $this->email        = trim( $email );
        $this->access_token = trim( $access_token );
    }

    /**
     * Generate a base64-encoded OAuth token string for SMTP XOAUTH2 authentication.
     *
     * @since 1.0.0
     *
     * @return string The base64-encoded XOAUTH2 token string.
     */
    public function getOauth64(): string {
        $soh = chr( 1 );
        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- Required by XOAUTH2 protocol.
        return base64_encode(
            'user=' . $this->email .
            $soh . 'auth=Bearer ' . $this->access_token .
            $soh . $soh
        );
    }
}
