<?php

// Microsoft 365 takes only OAuth for IMAP and SMTP, and Ivy holds the person's sign-in
// (Settings → Connected accounts), so Roundcube never shows Microsoft's page itself.
class ivy_microsoft extends rcube_plugin
{
    // Ivy refreshes with Microsoft on every ask, so a token is reused until close to its expiry.
    private const REFRESH_MARGIN = 300;
    private const SIGNED_OUT = 'ivy_microsoft_off';

    private ?array $token = null;
    private bool $signing_in = false;
    private bool $signing_out = false;

    public function init()
    {
        $this->add_hook('startup', [$this, 'startup']);
        $this->add_hook('authenticate', [$this, 'authenticate']);
        $this->add_hook('login_after', [$this, 'login_after']);
        $this->add_hook('logout_after', [$this, 'logout_after']);
        $this->add_hook('storage_init', [$this, 'storage_init']);
        $this->add_hook('smtp_connect', [$this, 'smtp_connect']);
        $this->add_hook('template_object_loginform', [$this, 'loginform']);
    }

    public function startup($args)
    {
        if (rcube_utils::get_input_string('_ivy_microsoft', rcube_utils::INPUT_GET)) {
            rcube_utils::setcookie(self::SIGNED_OUT, '', time() - 3600);
            unset($_COOKIE[self::SIGNED_OUT]);
        }
        // Roundcube clears the session before `logout_after`.
        $this->signing_out = $args['task'] === 'logout' && isset($_SESSION['ivy_microsoft_expires']);
        $signed_out = !empty($_COOKIE[self::SIGNED_OUT]);
        if ($args['task'] === 'login' && empty($args['action']) && empty($_SESSION['user_id']) && !$signed_out) {
            $this->token = $this->ask_ivy();
            if ($this->token) {
                $args['action'] = 'login';
            }
        } elseif ($args['task'] !== 'logout' && !empty($_SESSION['user_id'])
            && isset($_SESSION['ivy_microsoft_expires'])
            && $_SESSION['ivy_microsoft_expires'] - time() <= self::REFRESH_MARGIN) {
            $token = $this->ask_ivy();
            if ($token && strcasecmp($token['account'], $_SESSION['username']) !== 0) {
                // The person connected another Microsoft account in Ivy: open that mailbox.
                rcmail::get_instance()->kill_session();
                $this->token = $token;
                $args['task'] = 'login';
                $args['action'] = 'login';
            } elseif ($token) {
                $_SESSION['password'] = rcmail::get_instance()->encrypt('Bearer ' . $token['access_token']);
                $_SESSION['ivy_microsoft_expires'] = $token['expires'];
            }
        }

        return $args;
    }

    public function authenticate($args)
    {
        if ($this->token) {
            $args['user'] = $this->token['account'];
            $args['pass'] = 'Bearer ' . $this->token['access_token'];
            // Microsoft's tokens outgrow the cap meant for typed passwords.
            rcmail::get_instance()->config->set('login_password_maxlen', strlen($args['pass']));
            $args['host'] = rcmail::get_instance()->config->get('ivy_microsoft_host');
            // Ivy signed the person in; there is no form whose request token to check.
            $args['cookiecheck'] = false;
            $args['valid'] = true;
            $this->signing_in = true;
        }

        return $args;
    }

    public function login_after($args)
    {
        if ($this->signing_in) {
            $_SESSION['ivy_microsoft_expires'] = $this->token['expires'];
        }

        return $args;
    }

    public function logout_after($args)
    {
        if ($this->signing_out) {
            rcube_utils::setcookie(self::SIGNED_OUT, '1');
        }

        return $args;
    }

    public function storage_init($options)
    {
        if ($this->signing_in) {
            $options['auth_type'] = 'XOAUTH2';
        } elseif (isset($_SESSION['ivy_microsoft_expires'])) {
            $options['auth_type'] = 'XOAUTH2';
        }

        return $options;
    }

    public function smtp_connect($options)
    {
        if (isset($_SESSION['ivy_microsoft_expires'])) {
            $options['smtp_user'] = '%u';
            $options['smtp_pass'] = '%p';
            $options['smtp_auth_type'] = 'XOAUTH2';
        }

        return $options;
    }

    public function loginform($args)
    {
        $this->add_texts('localization/');
        $hint = empty($_COOKIE[self::SIGNED_OUT])
            ? html::p(['class' => 'hint'], rcube::Q($this->gettext('signin_in_ivy')))
            : html::p(['class' => 'hint'], html::a(
                ['href' => './?_task=login&_ivy_microsoft=1'],
                rcube::Q($this->gettext('open_mailbox'))
            ));
        $args['content'] = $hint . $args['content'];

        return $args;
    }

    private function ask_ivy(): ?array
    {
        $api = getenv('IVY_API_URL');
        if (!$api) {
            return null;
        }
        $path = '/v1/organisations/' . rawurlencode(getenv('IVY_ORGANISATION_ID'))
            . '/spaces/' . rawurlencode(getenv('IVY_WORKSPACE_ID'))
            . '/apps/' . rawurlencode(getenv('IVY_APP_ID'))
            . '/instances/' . rawurlencode(getenv('IVY_INSTANCE_ID'))
            . '/secrets/microsoft/token';
        $curl = curl_init('http://ivy' . $path);
        $socket = str_starts_with($api, '@') ? CURLOPT_ABSTRACT_UNIX_SOCKET : CURLOPT_UNIX_SOCKET_PATH;
        curl_setopt_array($curl, [
            $socket => ltrim($api, '@'),
            CURLOPT_NOPROXY => '*',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 20,
        ]);
        $body = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        curl_close($curl);
        $token = is_string($body) ? json_decode($body, true) : null;
        if ($status !== 200 || empty($token['access_token']) || empty($token['account'])) {
            $code = $token['error']['code'] ?? "HTTP $status";
            if ($code !== 'app_secret_missing') {
                rcube::write_log('errors', "ivy_microsoft: no token from Ivy ($code)");
            }

            return null;
        }
        $token['expires'] = strtotime($token['expires_at']) ?: time();

        return $token;
    }
}
