<?php
/**
 * MachForm
 * 
 * © 2007–2025 Appnitro Software. All rights reserved.
 * 
 * This source code is proprietary and may not be copied, modified,
 * or distributed in any form without express written permission from Appnitro Software.
 * 
 * License information: https://www.machform.com/license-agreement/
 */
	require('config.php');
	require('lib/db-session-handler.php');
	require('includes/init.php');
	require('includes/db-core.php');
	require('includes/helper-functions.php');
	require('includes/check-session.php');

	require('includes/filter-functions.php');
    require('lib/phpmailer/vendor/autoload.php');
	
	$oauth_code = mf_sanitize($_GET['code'] ?? '');
	
	if(empty($oauth_code)){
		die("This file can't be opened directly.");
	}

	$dbh         = mf_connect_db();
	$mf_settings = mf_get_settings($dbh);

    try {
        $provider = new \Greew\OAuth2\Client\Provider\Azure([
            'clientId' => $mf_settings['smtp_ms365_client_id'],
            'clientSecret' => $mf_settings['smtp_ms365_client_secret'],
            'tenantId' => $mf_settings['smtp_ms365_tenant_id'],
            'redirectUri' => $mf_settings['base_url']."oauth_ms.php",
            'accessType' => 'offline'
        ]);

        $token = $provider->getAccessToken(
            'authorization_code',
            [
                'code' => $_GET['code']
            ]
        );

        $refresh_token = $token->getRefreshToken();
        
        //save refresh token into ap_settings table
        $query = "update `".MF_TABLE_PREFIX."settings` SET smtp_ms365_refresh_token = ?;";
        $params = array($refresh_token);

        mf_do_query($query,$params,$dbh);

        $_SESSION['MF_SUCCESS'] = 'Microsoft 365 connected successfully!';
    } catch (\Exception $e) {
        unset($_SESSION['MF_SUCCESS']);
        $_SESSION['MF_ERROR'] = 'Error connecting to Microsoft 365: ' . $e->getMessage();
    }

    header("Location: ".mf_get_dirname($_SERVER['PHP_SELF'])."/main_settings.php");
    exit;
?>