<?php

namespace Office365PostSMTP;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

class Transport extends \PostmanAbstractModuleTransport implements \PostmanModuleTransport {

    const SLUG = 'office365_api';
    const PORT = 443;
    const HOST = 'smtp.office365.com';
    const PRIORITY = 8000;
    const AUTH_OPTIONS = 'postman_office365_auth_options';
    const AUTH_SECTION = 'postman_office365_auth_section';

    const OPTION_APP_ID = 'office365_app_id';
    const OPTION_APP_PASSWORD = 'office365_app_password';

    /**
     *
     * @param mixed $rootPluginFilenameAndPath
     */
    public function __construct( $rootPluginFilenameAndPath ) {
        parent::__construct( $rootPluginFilenameAndPath );

        // add a hook on the plugins_loaded event
        add_action( 'admin_init', array(
            $this,
            'on_admin_init',
        ) );
        
        add_action( 'wp_ajax_save_office365_oneclick_toggle', array( $this, 'ajax_save_office365_oneclick_toggle' ) );

        $this->options = get_option( \PostmanOptions::POSTMAN_OPTIONS );
    }

    public function getProtocol() {
        return 'https';
    }

    // this should be standard across all transports
    public function getSlug() {
        return self::SLUG;
    }
    public function getName() {
        return __( 'Office365 API', 'post-smtp-office365' );
    }
    /**
     * v0.2.1
     *
     * @return string
     */
    public function getHostname() {
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

        return self::HOST;
    }
    /**
     * v0.2.1
     *
     * @return int
     */
    public function getPort() {
        return self::PORT;
    }
    /**
     * v1.7.0
     *
     * @return string
     */
    public function getTransportType() {
        return 'office365_api';
    }

    /**
     * (non-PHPdoc)
     *
     * @see PostmanModuleTransport::createMailEngine()
     */
    public function createMailEngine() {

        require_once 'Engine.php';

        $engine = new Engine();
        
        return $engine;
    }
    public function getDeliveryDetails() {
        /* translators: where (1) is the secure icon and (2) is the transport name */
        return sprintf( __( 'Post SMTP will send mail via the <b>%1$s %2$s</b>.', 'post-smtp-office365' ), '🔐', $this->getName() );
    }

    /**
     *
     * @param mixed $data
     */
    public function prepareOptionsForExport( $data ) {
        $data = parent::prepareOptionsForExport( $data );
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

        $data [ self::OPTION_APP_ID ] = base64_decode( $options[ self::OPTION_APP_ID ] );
        $data [ self::OPTION_APP_PASSWORD ] = base64_decode( $options[ self::OPTION_APP_PASSWORD ] );

        return $data;
    }

    /**
     * Validate the settings when you save
     *
     * @return array
     */
    protected function validateTransportConfiguration() {
        $messages = parent::validateTransportConfiguration();
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

        // Check if Office One Click is enabled
        $post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
        $extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : [];
        $office365_oneclick_enabled = in_array( 'microsoft-one-click', $extensions );

        // Skip validation if Office One Click is enabled
        if ( !$office365_oneclick_enabled ) {
            $access_key = isset( $options[ self::OPTION_APP_ID ] ) ? $options[ self::OPTION_APP_ID ]: '';
            $secret_access_key = isset( $options[ self::OPTION_APP_PASSWORD ] ) ? $options[ self::OPTION_APP_PASSWORD ] : '';

            if ( empty( $access_key ) ) {
                array_push( $messages, __( 'Application (client) ID can not be empty', 'post-smtp-office365' ) . '.' );
                $this->setNotConfiguredAndReady();
            }

            if ( empty( $secret_access_key ) ) {
                array_push( $messages, __( 'Value (APP Secret) can not be empty', 'post-smtp-office365' ) . '.' );
                $this->setNotConfiguredAndReady();
            }
        }

        return $messages;
    }

    /**
     * (non-PHPdoc)
     *
     * @see PostmanModuleTransport::getConfigurationBid()
     */
    public function getConfigurationBid( \PostmanWizardSocket $hostData, $userAuthOverride, $originalSmtpServer ) {
        $recommendation = array();
        $recommendation ['priority'] = 0;
        $recommendation ['transport'] = self::SLUG;
        $recommendation ['hostname'] = null; // scribe looks this
        $recommendation ['label'] = $this->getName();
        if ( $hostData->hostname == $this->getHostname() && $hostData->port == self::PORT ) {
            $recommendation ['priority'] = self::PRIORITY;
            /* translators: where variables are (1) transport name (2) host and (3) port */
            $recommendation ['message'] = sprintf( __( ('Postman recommends the %1$s to host %2$s on port %3$d.') ), $this->getName(), $this->getHostname(), self::PORT );
        }
        return $recommendation;
    }

    /**
     *
     * @param mixed $hostname
     * @param mixed $response
     */
    public function populateConfiguration( $hostname ) {
        $response = parent::populateConfiguration( $hostname );
        return $response;
    }

    /**
     * Print The option to select when you choose the transport in the wizard
     *
     * @param PostmanWizardSocket $socket
     * @param $winningRecommendation
     * @param $userSocketOverride
     * @param $userAuthOverride
     * @return array
     */
    public function createOverrideMenu( \PostmanWizardSocket $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride ) {
        $overrideItem = parent::createOverrideMenu( $socket, $winningRecommendation, $userSocketOverride, $userAuthOverride );
        // push the authentication options into the $overrideItem structure
        $overrideItem ['auth_items'] = array(
            array(
                'selected' => true,
                'name' => __( 'Office365 Credentials', 'post-smtp-office365' ),
                'value' => 'office365_api_key',
            ),
        );
        return $overrideItem;
    }

    /**
     * On admin init - create settings and run scripts
     */
    public function on_admin_init() {
        // only administrators should be able to trigger this
        if ( \PostmanUtils::isAdmin() ) {
            // Register sanitization for post_smtp_pro
            if (function_exists('register_setting')) {
                register_setting('post_smtp_pro', 'post_smtp_pro', 'post_smtp_pro_sanitize_extensions');
            }
            $this->addSettings();
            $this->registerStylesAndScripts();
            // Enqueue styles and scripts on the settings page
            add_action( 'admin_enqueue_scripts', array( $this, 'maybe_enqueue_assets' ) );
        }
    }
    
    /**
     * Conditionally enqueue assets on Post SMTP settings pages
     */
    public function maybe_enqueue_assets( $hook ) {
        // Check if we're on a Post SMTP settings page
        if ( isset( $_GET['page'] ) && strpos( $_GET['page'], 'postman' ) !== false ) {
            $this->enqueueScript();
        }
    }

	/**
	 * Create the settings for the plugin
	 */
	public function addSettings() {

		// The Auth section
		add_settings_section( 
			self::AUTH_SECTION, 
			__( 'Authentication', 'post-smtp-office365' ), 
			array( $this, 'printAuthSectionInfo' ), 
			self::AUTH_OPTIONS 
		);

        // Add One-Click Setup toggle field
        add_settings_field(
            'office365_oneclick_toggle',
            __( 'Enable One-Click Setup', 'post-smtp-office365' ),
            array( $this, 'renderOffice365OneClickToggle' ),
            self::AUTH_OPTIONS,
            self::AUTH_SECTION
        );

        // Add Microsoft Authorization button/section
        add_settings_field(
            'office365_custom_ui',
            __( 'Microsoft Authorization', 'post-smtp-office365' ),
            array( $this, 'renderOffice365SettingsUI' ),
            self::AUTH_OPTIONS,
            self::AUTH_SECTION
        );
        // Application (client) ID field
		add_settings_field( 
			self::OPTION_APP_ID, 
			__( 'Application (client) ID', 'post-smtp-office365' ), 
			array( $this, 'api_key_callback' ), 
			self::AUTH_OPTIONS, 
			self::AUTH_SECTION,
			['class' => 'office365-manual-field']
		);
		// Application Secret field
		add_settings_field( 
			self::OPTION_APP_PASSWORD, 
			__( 'Value (APP Secret)', 'post-smtp-office365' ), 
			array( $this, 'secret_key_callback' ), 
			self::AUTH_OPTIONS, 
			self::AUTH_SECTION,
			['class' => 'office365-manual-field']
		);

		// Redirect URI field (always present)
		add_settings_field( 
			'office365_redirect_uri', 
			__( 'Redirect URI', 'post-smtp-office365' ), 
			array( $this, 'redirect_uri' ), 
			self::AUTH_OPTIONS, 
			self::AUTH_SECTION,
			['class' => 'office365-manual-field']
		);
		
	}


    /**
     * Render the One-Click Setup toggle field
     */
    public function renderOffice365OneClickToggle() {
        $post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
        $extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : [];
        $enabled = in_array( 'microsoft-one-click', $extensions );

        // Determine if the current license plan is Business
        $is_business_plan = function_exists( 'pspro_fs' ) && pspro_fs()->is_plan( 'business' );
        ?>
        <label for="office365_oneclick_toggle_switch" style="margin-right:10px; cursor: hand;">
            <span class="ps-toggle-switch">
                <input type="hidden" name="post_smtp_pro[extensions][]" value="">
                <input
                    type="checkbox"
                    id="office365_oneclick_toggle_switch"
                    name="post_smtp_pro[extensions][]"
                    value="microsoft-one-click"
					<?php echo $enabled ? ' checked' : ''; ?>
                    data-business-plan-required="1"
                    data-is-business-plan="<?php echo $is_business_plan ? '1' : '0'; ?>"
                >
                <span class="ps-toggle-slider"></span>
            </span>
        </label>
        <span style="vertical-align:middle;"> <?php echo esc_html__( 'Enable the option for a quick and easy way to connect with Office 365 without the need of manually creating an app.', 'post-smtp-office365' ); ?> </span>
        <img id="office365_oneclick_gif" src="<?php echo esc_url( '/wp-content/plugins/post-smtp/Postman/Wizard/assets/css/images/office-once-click.gif' ); ?>" style="display:none; vertical-align:middle; margin-left:10px; cursor:pointer;position:absolute;left: 250px; top: 510px;" alt="<?php echo esc_attr( 'Office 365 One Click Demo' ); ?>" />
        <p class="description"> <?php echo esc_html__( 'When enabled, you can use the One-Click button to connect with Office 365. Otherwise, fill in the manual details below.', 'post-smtp-office365' ); ?> </p>
        <?php
        // Output the upgrade popup markup so JS can trigger it when needed (only once on the settings page).
        $this->render_office365_business_plan_popup();
    }
		
	/**
	 * Render UI inside settings page without polluting the main response.
	 */
    public function renderOffice365SettingsUI() {
        $post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
        $extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : [];
        $enabled = in_array( 'microsoft-one-click', $extensions );
        if ( $enabled ) {
            if ( class_exists( 'Post_Smtp_Office365' ) ) {
                $office365 = new \Post_Smtp_Office365();
                $office365->renderOffice365AuthButtons();
            } else {
                echo '<p>' . esc_html__( 'Office 365 integration is not available.', 'post-smtp-office365' ) . '</p>';
            }
        } else {
            // Show manual details (Authorized JavaScript Origin, etc.)
            echo '<div class="office365-manual-details">';
            echo '<p><strong>' . esc_html__( 'Manual Setup Required', 'post-smtp-office365' ) . '</strong></p>';
            echo '<p>' . esc_html__( 'Please fill in the Application (client) ID, Value (APP Secret), and Redirect URI fields below to connect manually.', 'post-smtp-office365' ) . '</p>';
            echo '<ul>';
            echo '<li><strong>' . esc_html__( 'Authorized JavaScript Origin:', 'post-smtp-office365' ) . '</strong> ' . esc_html( site_url() ) . '</li>';
            echo '<li><strong>' . esc_html__( 'Authorized Redirect URI:', 'post-smtp-office365' ) . '</strong> ' . esc_html( site_url() . '/wp-admin/' ) . '</li>';
            echo '</ul>';
            echo '</div>';
        }
    }

    /**
     * Render the Business plan upgrade popup markup (copied from free plugin wizard style).
     *
     * This markup is hidden by default and can be triggered via JS when a non-Business
     * user attempts to enable Microsoft 365 One-Click.
     */
    public function render_office365_business_plan_popup() {
        // Only render once per page load.
        static $rendered = false;
        if ( $rendered ) {
            return;
        }
        $rendered = true;
        ?>
        <div class="ps-pro-popup-overlay" style="display:none;">
            <div class="ps-pro-popup-container">
                <div class="ps-pro-popup-outer">
                    <div class="ps-pro-popup-body">
                        <span class="dashicons dashicons-no-alt ps-pro-close-popup"></span>
                        <div class="ps-pro-popup-content">
                            <img src="<?php echo esc_url( POST_SMTP_URL . '/Postman/Wizard/assets/images/ms365-popup.png' ); ?>" class="ps-pro-for-img" />
                            <h1>
                                <?php esc_html_e( 'Ready to Supercharge Your Emails with', 'post-smtp-pro' ); ?>
                                <span class="ps-pro-for"><?php esc_html_e( 'One‑Click Microsoft Mailer Setup?', 'post-smtp-pro' ); ?></span>
                            </h1>
                            <h4>
                                <?php
                                printf(
                                    /* translators: 1: strong HTML open, 2: strong HTML close */
                                    esc_html__( 'Unlock this %1$sPro Feature NOW%2$s and get a', 'post-smtp-pro' ),
                                    '<strong>',
                                    '</strong>'
                                );
                                ?>
                            </h4>
                            <span class="smily">🤩 <strong><?php esc_html_e( 'HUGE 25% discount!', 'post-smtp-pro' ); ?></strong> 🤩</span>

                            <div <?php echo postman_is_bfcm()
                                ? 'style="background: url(' . esc_url( POST_SMTP_ASSETS . 'images/bfcm-2024/popup.png' ) . '); background-size: cover; margin: 20px 0 5px 0; padding: 16px 0; position: relative;"'
                                : 'class="ps-pro-promo-area"'; ?>>

                                <div <?php echo postman_is_bfcm() ? 'style="background:#fbb81f;"' : ''; ?> class="ps-pro-coupon">
                                    <b <?php echo postman_is_bfcm() ? 'style="color:#1a3b63;"' : ''; ?>>
                                        <?php esc_html_e( 'Use Coupon:', 'post-smtp-pro' ); ?>
                                        <span class="ps-pro-coupon-code">
                                            <?php echo esc_html( postman_is_bfcm() ? 'BFCM2024' : 'GETSMTPPRO' ); ?>
                                        </span>
                                        <span class="copy-icon ps365-click-to-copy">
                                            <svg width="7" height="7" viewBox="0 0 7 7" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M6.1261 6.7273H3.47361C3.25716 6.7273 3.04957 6.64131 2.89651 6.48825C2.74345 6.3352 2.65746 6.12761 2.65746 5.91115V3.25867C2.65746 3.04221 2.74345 2.83462 2.89651 2.68156C3.04957 2.5285 3.25716 2.44252 3.47361 2.44252H6.1261C6.34255 2.44252 6.55015 2.5285 6.7032 2.68156C6.85626 2.83462 6.94225 3.04221 6.94225 3.25867V5.91115C6.94165 6.12742 6.85547 6.33466 6.70254 6.48759C6.54961 6.64052 6.34237 6.7267 6.1261 6.7273ZM3.47361 2.89593C3.42598 2.89593 3.37881 2.90531 3.3348 2.92354C3.29079 2.94177 3.25081 2.96849 3.21712 3.00217C3.18344 3.03586 3.15672 3.07584 3.13849 3.11985C3.12026 3.16386 3.11088 3.21103 3.11088 3.25867V5.91115C3.11088 6.00735 3.1491 6.09961 3.21712 6.16764C3.28515 6.23567 3.37741 6.27388 3.47361 6.27388H6.1261C6.2223 6.27388 6.31456 6.23567 6.38259 6.16764C6.45061 6.09961 6.48883 6.00735 6.48883 5.91115V3.25867C6.48883 3.16246 6.45061 3.0702 6.38259 3.00217C6.31456 2.93415 6.2223 2.89593 6.1261 2.89593H3.47361ZM1.932 4.43755C1.932 4.37742 1.90811 4.31976 1.8656 4.27724C1.82308 4.23472 1.76542 4.21084 1.70529 4.21084H1.41057C1.31437 4.21084 1.22211 4.17262 1.15408 4.1046C1.08605 4.03657 1.04784 3.94431 1.04784 3.84811V1.19562C1.04784 1.09942 1.08605 1.00716 1.15408 0.939131C1.22211 0.871105 1.31437 0.832889 1.41057 0.832889H4.06305C4.11069 0.832889 4.15786 0.842271 4.20187 0.8605C4.24588 0.878729 4.28586 0.905448 4.31955 0.939131C4.35323 0.972814 4.37995 1.0128 4.39818 1.05681C4.41641 1.10082 4.42579 1.14799 4.42579 1.19562V1.49034C4.42579 1.55047 4.44967 1.60813 4.49219 1.65065C4.53471 1.69317 4.59237 1.71705 4.6525 1.71705C4.71262 1.71705 4.77029 1.69317 4.8128 1.65065C4.85532 1.60813 4.8792 1.55047 4.8792 1.49034V1.19562C4.8792 0.979166 4.79322 0.771575 4.64016 0.618517C4.4871 0.46546 4.27951 0.379473 4.06305 0.379473H1.41057C1.1943 0.380071 0.987055 0.46625 0.834127 0.619178C0.681199 0.772106 0.59502 0.97935 0.594421 1.19562V3.84811C0.594421 4.06456 0.680408 4.27215 0.833466 4.42521C0.986524 4.57827 1.19411 4.66426 1.41057 4.66426H1.70529C1.76542 4.66426 1.82308 4.64037 1.8656 4.59785C1.90811 4.55534 1.932 4.49767 1.932 4.43755Z" fill="#5E7CBF"/>
                                            </svg>
                                        </span>
                                    </b>
                                </div>

                                <div id="ps-pro-code-copy-notification">
                                    <?php esc_html_e( 'Code Copied', 'post-smtp-pro' ); ?>
                                    <span class="dashicons dashicons-yes"></span>
                                </div>
                            </div>

                            <div>
                                <a href="<?php echo esc_url( postman_is_bfcm()
                                    ? 'https://postmansmtp.com/cyber-monday-sale?utm_source=plugin&utm_medium=section_name&utm_campaign=BFCM&utm_id=BFCM_2024'
                                    : 'https://postmansmtp.com/pricing/?utm_source=plugin&utm_medium=wizard&utm_campaign=plugin'
                                ); ?>" target="_blank" class="button button-primary ps-yellow-btn ps-pro-product-url">
                                    <?php esc_html_e( 'CLAIM 25% OFF NOW', 'post-smtp-pro' ); ?>
                                    <span class="dashicons dashicons-arrow-right-alt2"></span>
                                </a>
                            </div>

                            <div>
                                <a href="#" class="ps-pro-close-popup" style="color:#6A788B;font-size:12px;">
                                    <?php esc_html_e( 'Already purchased?', 'post-smtp-pro' ); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }


    public function printAuthSectionInfo() {
        /* Translators: Where (1) is the service URL and (2) is the service name and (3) is a api key URL */
        printf( '<p id="wizard_office365_auth_help">%s</p>', sprintf( __( 'Create an account at <a href="%1$s" target="_blank">%2$s</a> and enter the account id and secret below.', 'post-smtp-office365' ), 'https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps', 'https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps' ) );
    }


    public function api_key_callback() {
        $app_id = isset( $this->options[ Transport::OPTION_APP_ID ] ) ? $this->options[ Transport::OPTION_APP_ID ] : '';
        printf( '<input type="password" autocomplete="off" id="' . self::OPTION_APP_ID . '" name="postman_options[' . self::OPTION_APP_ID . ']" value="%s" size="60" class="required" placeholder="%s"/>', null !== $app_id ? esc_attr( \PostmanUtils::obfuscatePassword( base64_decode( $app_id ) ) ) : '', __( 'Required', 'post-smtp-office365' ) );
        print '<input type="button" id="toggle' . self::OPTION_APP_ID . '" value="Show Password" class="button button-secondary" style="visibility:hidden" />';
    }

    public function secret_key_callback() {
        $app_password = isset( $this->options[ Transport::OPTION_APP_PASSWORD ] ) ? $this->options[ Transport::OPTION_APP_PASSWORD ]: '';
        printf( '<input type="password" autocomplete="off" id="' . self::OPTION_APP_PASSWORD . '" name="postman_options[' . self::OPTION_APP_PASSWORD . ']" value="%s" size="60" class="required" placeholder="%s"/>', null !== $app_password ? esc_attr( \PostmanUtils::obfuscatePassword( base64_decode( $app_password )  ) ) : '', __( 'Required', 'post-smtp-office365' ) );
        print '<input type="button" id="toggle' . self::OPTION_APP_PASSWORD . '" value="Show Password" class="button button-secondary" style="visibility:hidden" />';
    }


    /**
     * Prints the Redirect URI
     * 
     * @since 1.0.2
     * @version 1.0
     */
    public function redirect_uri() {

        printf( 
            '<input type="text" disabled id="psses-redirect-uri" value="%s" size="60" />', 
            esc_attr( site_url() . '/wp-admin/' ) 
        );

    }

    /**
     */
    public function registerStylesAndScripts() {
        // register the stylesheet and javascript external resources
        $pluginData = apply_filters( 'postman_get_plugin_metadata', null );
        $slug = self::SLUG;
        
        // Register JS
        wp_register_script( "post_smtp_{$slug}", PSO365_ASSETS . 'js/script.js', array(
            \PostmanViewController::JQUERY_SCRIPT,
            'jquery_validation',
            \PostmanViewController::POSTMAN_SCRIPT
        ), $pluginData ['version'], true );
    }

    /**
     */
    public function enqueueScript() {
        $slug = self::SLUG;
        // Localize nonce for AJAX before enqueue to ensure it prints
        wp_localize_script( "post_smtp_{$slug}", 'office365_oneclick_toggle', array(
            'nonce' => wp_create_nonce( 'office365_oneclick_toggle' )
        ) );
        wp_enqueue_script( "post_smtp_{$slug}" );
    }

    /**
     * Print Wizard Settings
     */
    public function printWizardAuthenticationStep() {
        print '<section class="wizard_office365">';
        $this->printAuthSectionInfo();
        printf( '<label for="' . self::OPTION_APP_ID . '">%s</label>', __( 'Application (client) ID', 'post-smtp-office365' ) );
        print '<br />';
        print $this->api_key_callback();
        printf( '<label for="' . self::OPTION_APP_PASSWORD . '">%s</label>', __( 'Value (APP Secret)', 'post-smtp-office365' ) );
        print '<br />';
        print $this->secret_key_callback();
        printf( '<label for="psses-redirect-uri">%s</label>', __( 'Redirect URI', 'post-smtp-office365' ) );
        print '<br />';
        $this->redirect_uri();
        print '<br />';
        print $this->documentation();
        print '</section>';
    }
	
    /**
     * Returns Logo URL 
     * 
     * @since 1.0
     * @version 1.0
     */
	public function getLogoURL() {
		return PSO365_ASSETS . 'images/logo.png';
	}

    /**
     * Show Video and documentation to user on wizard
     * 
     * @since 1.0.1
     * @version 1.0 
     */
    public function documentation() {

        $content = '
        <div class="pso365-documentation">
            <div>
                <iframe width="300" height="200" src="https://www.youtube.com/embed/ze4mMraEvwQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
            </div>
            <div>
                <a href="https://postmansmtp.com/documentation/#configure-office-365-integration" target="_blank">Stuck in Setup?</a>
            </div>
        </div>
        ';

        return $content; 

    }


    /**
     * Checks is configured and ready or not
     * 
     * @since 1.0.2
     * @version 1.0
     */
	public function isConfiguredAndReady() {
		$isReady = false;
		$options = get_option( \PostmanOptions::POSTMAN_OPTIONS );

		// Check for Office 365 One-Click enabled setting.
		$post_smtp_pro_options = get_option( 'post_smtp_pro', [] );
		$extensions = isset( $post_smtp_pro_options['extensions'] ) ? $post_smtp_pro_options['extensions'] : [];
		$office365_oneclick_enabled = in_array( 'microsoft-one-click', $extensions );

		if ( $office365_oneclick_enabled ) {
			$config = get_option( \Post_Smtp_Office365::OAUTH_OPTIONS );
			if ( ! empty( $config['refresh_token'] ) ) {
				$isReady = true;
			}
		} else {
			// Check regular conditions for configuration readiness.
			if (
				( isset( $options[self::OPTION_APP_ID] ) && !empty( $options[self::OPTION_APP_ID] ) )
				&&
				( isset( $options[self::OPTION_APP_PASSWORD] ) && !empty( $options[self::OPTION_APP_PASSWORD] ) )
				&&
				( $this->has_granted() )
			) {
				$isReady = true;
			}
		}

		return $isReady;
	}


    /**
     * Checks is granted or not
     * 
     * @since 1.0.2
     * @version 1.0
     */
    public function has_granted() {

        $has_granted = true;
        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );
        $config = get_option( \Post_Smtp_Office365::OAUTH_OPTIONS );

        if( 
            empty( $config['refresh_token'] ) 
            && 
            ( isset( $options[self::OPTION_APP_ID] ) && !empty( $options[self::OPTION_APP_ID] ) ) 
            && 
            ( isset( $options[self::OPTION_APP_PASSWORD] ) && !empty( $options[self::OPTION_APP_PASSWORD] ) )
        ) {
            $has_granted = false;
        }

        return $has_granted;

    }


    /**
	 * Returns the HTML of not granted
	 * 
	 * @since 1.0.2
	 * @version 1.0
	 */
    public function get_not_granted_notice() {

        $options = get_option( \PostmanOptions::POSTMAN_OPTIONS );
        $config = get_option( \Post_Smtp_Office365::OAUTH_OPTIONS );
        
        $oauthClient = (new \Post_Smtp_Office365())->get_office365_configuration();

        $PostmanClient = new \OAuthOffice365( $oauthClient );
        // Generate the auth URL
        $state = get_transient( \Post_Smtp_Office365::STATE );
        if ( $state === false ) {
            $state = set_transient( \Post_Smtp_Office365::STATE, bin2hex(random_bytes( 32 / 2 )), 5 * MINUTE_IN_SECONDS );
        }

        $authorizationUrl = $PostmanClient->getOffice365AuthURL( array( 'state' => $state ) );

        return array(
			'message'	=> __( 'You have configured OAuth 2.0 authentication, but have not received permission to use it.', 'post-smtp-office365' ),
			'url_text'	=> __( 'Grant Office365 Permission', 'post-smtp-office365' ),
			'url'		=> $authorizationUrl
		);

    }
    
    /**
     * AJAX handler for Office 365 One Click toggle save
     */
    public function ajax_save_office365_oneclick_toggle() {
        // Verify nonce if provided
        if ( isset( $_POST['_ajax_nonce'] ) ) {
            check_ajax_referer( 'office365_oneclick_toggle' );
        }
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => __( 'Unauthorized', 'post-smtp-office365' ) ), 403 );
        }

        $enabled = isset( $_POST['enabled'] ) && $_POST['enabled'] == '1';

        // Only Business plan can enable Office 365 One-Click
        $is_business_plan = function_exists( 'pspro_fs' ) && pspro_fs()->is_plan( 'business' );
        if ( $enabled && ! $is_business_plan ) {
            wp_send_json_error(
                array(
                    'message'      => __( 'Office 365 One-Click Setup is available on the Business plan only.', 'post-smtp-office365' ),
                    'upgrade_url'  => 'https://postmansmtp.com/pricing/',
                    'is_business'  => (int) $is_business_plan,
                ),
                403
            );
        }

        $options = get_option( 'post_smtp_pro', array() );
        $extensions = isset( $options['extensions'] ) && is_array( $options['extensions'] ) ? $options['extensions'] : array();

        if ( $enabled ) {
            if ( ! in_array( 'microsoft-one-click', $extensions, true ) ) {
                $extensions[] = 'microsoft-one-click';
            }
        } else {
            $extensions = array_diff( $extensions, array( 'microsoft-one-click' ) );
        }
        // Clean values
        $options['extensions'] = array_values( array_unique( array_filter( $extensions ) ) );
        update_option( 'post_smtp_pro', $options );

        $auth_ui_html = '';
        if ( $enabled ) {
            if ( class_exists( '\\Post_Smtp_Office365' ) ) {
                ob_start();
                $office365 = new \Post_Smtp_Office365();
                $office365->renderOffice365AuthButtons();
                $auth_ui_html = ob_get_clean();
            } else {
                $auth_ui_html = '<p>' . esc_html__( 'Office 365 integration is not available.', 'post-smtp-office365' ) . '</p>';
            }
        }

        wp_send_json_success( array(
            'enabled' => $enabled ? 1 : 0,
            'auth_ui_html' => $auth_ui_html,
        ) );
    }

}