<?php 

class PSP_Active_Deactivate {

    /**
     * PSP_Active_Deactivate Constructor
     * 
     * @since 1.0.0
     */
    public function __construct() {

        register_activation_hook( POST_SMTP_PRO_FILE, array( $this, 'activate_plugins' ) );
        register_deactivation_hook( POST_SMTP_PRO_FILE, array( $this, 'clear_cron_event' ) );
        add_action( 'admin_init', array( $this, 'handle_version_upgrade' ), 1 );

    }

    /**
     * Activate the plugin
     * 
     * @since 1.0.0
     */
    public function activate_plugins() {
        
        $this->report_and_tracking();
        $this->microsoft_365();
        $this->zohomail();
        $this->gmail_one_click();
		$this->office365_one_click();

       update_option( 'post_smtp_pro_version', POST_SMTP_PRO_VERSION );

    }

    /**
     * Handles version-based upgrade routines.
     *
     * @since 1.5.0
     */
    public function handle_version_upgrade() {
        // Only run in admin to avoid touching front‑end requests.
        if ( ! is_admin() ) {
            return;
        }
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $stored_version = get_option( 'post_smtp_pro_version', '' );
        if ( empty( $stored_version ) ) {
            $stored_version = '0.0.0';
        }

        if ( version_compare( $stored_version, POST_SMTP_PRO_VERSION, '>=' ) ) {
            return;
        }

        $this->gmail_one_click();
        $this->office365_one_click();
        update_option( 'post_smtp_pro_version', POST_SMTP_PRO_VERSION );
    }

    /**
     * Activate Report and Tracking
     * 
     * @since 1.0.0
     */
    public function report_and_tracking() {

        if( !class_exists( 'Post_SMTP_Report_And_Tracking' ) ) {

            require_once POST_SMTP_PRO_PATH . 'extensions/report-and-tracking/report-and-tracking.php';

            Post_SMTP_Report_And_Tracking::get_instance()->activate_plugin();

        } 

    }

    /**
     * Activate Microsoft 365
     * 
     * @since 1.0.0
     */
    public function microsoft_365() {
        
        $this->post_smtp_office365_activate();

    }

    /**
     * Activate Zoho Mail
     * 
     * @since 1.0.0
     */
    public function zohomail() {

        if( !class_exists( 'PostSMTP_ZohoMail' ) ) {

            require_once POST_SMTP_PRO_PATH . 'extensions/zoho-mail/zoho-mail.php';

            postsmtp_zohomail_activation();
        
        } 

    }
	
	 /**
     * Activate  Office 36 One Click.
     *
     * Fetches the Office 365 OAuth URL from the API and stores it in the WordPress options table.
     *
     * @since 1.5
     */
    public function office365_one_click() {
       		// Get a fresh Office 365 OAuth auth URL (includes a fresh nonce).
		if ( function_exists( 'post_smtp_get_office365_auth_url' ) ) {
			$auth_url = post_smtp_get_office365_auth_url();

			if ( ! empty( $auth_url ) ) {
				update_option( 'post_smtp_office365_auth_url', esc_url_raw( $auth_url ) );
			}
		}   
    }



    /**
     * Sets default OAuth options for Office 365 integration on plugin activation.
     *
     * This function initializes and saves the required OAuth settings, including 
     * redirect URI, scopes, and endpoints, into the WordPress database under 
     * `Post_Smtp_Office365::OAUTH_OPTIONS`.
     *
     * @since 1.2.3
     * @version 1.0
     */
    public function post_smtp_office365_activate() {
        $redirect_uri = admin_url();
        $options = [
            'OAUTH_REDIRECT_URI'       => $redirect_uri,
            'OAUTH_SCOPES'             => 'openid profile offline_access Mail.Send Mail.Send.Shared',
            'OAUTH_AUTHORITY'          => 'https://login.microsoftonline.com/common',
            'OAUTH_AUTHORIZE_ENDPOINT' => '/oauth2/v2.0/authorize',
            'OAUTH_TOKEN_ENDPOINT'     => '/oauth2/v2.0/token',
        ];

        update_option( 'postman_office365_oauth' , $options );
    }
    
	/**
	 * Activate Gmail One Click.
	 *
	 * Fetches the Gmail OAuth URL from the API and stores it in the WordPress options table.
	 * This is primarily used on plugin activation; at runtime the URL is also refreshed
	 * when the "Sign in with Google" button is rendered to ensure a fresh nonce.
	 *
	 * @since 1.3.0
	 */
	public function gmail_one_click() {
		// Get a fresh Gmail OAuth auth URL (includes a fresh nonce).
		if ( function_exists( 'post_smtp_get_gmail_auth_url' ) ) {
			$auth_url = post_smtp_get_gmail_auth_url();

			if ( ! empty( $auth_url ) ) {
				update_option( 'post_smtp_gmail_auth_url', esc_url_raw( $auth_url ) );
			}
		}
	}

    /**
     * Clears the scheduled custom cron event for batch email processing.
     *
     * This function checks if the cron event ('post_smtp_batch_cron_hook') is scheduled.
     * If found, it unschedules the event, effectively stopping the batch email cron job.
     *
     * This is useful for cleaning up scheduled events when disabling the batch process
     * or when the plugin is deactivated.
     * 
     * @since 1.3.0
     */
    public function clear_cron_event() {
        // Get the next scheduled timestamp for the custom cron event.
        $timestamp = wp_next_scheduled( 'post_smtp_batch_cron_hook' );
        
        // If the event is scheduled, unschedule it.
        if ( $timestamp ) {
            wp_unschedule_event( $timestamp, 'post_smtp_batch_cron_hook' );
        }
		
		// Check and modify 'post_smtp_pro' option if needed.
		$options = get_option( 'post_smtp_pro' );

		if ( isset( $options['extensions'] ) && is_array( $options['extensions'] ) ) {
			$key = array_search( 'gmail-oneclick', $options['extensions'], true );

			if ( $key !== false ) {
				unset( $options['extensions'][ $key ] );

				// Reindex the array to keep it clean (optional)
				$options['extensions'] = array_values( $options['extensions'] );

				// Update the option
				update_option( 'post_smtp_pro', $options );
			}
		}
    }
}

/**
 * Returns a fresh Gmail OAuth "auth_url" from the Post SMTP connect API.
 *
 * This helper generates a new nonce and passes it to the remote endpoint, which
 * bakes the nonce into the redirect URL. That nonce is then verified in
 * `handle_gmail_oauth_redirect()` when Google redirects back.
 *
 * The returned URL is also stored in the `post_smtp_gmail_auth_url` option for
 * backward compatibility with any existing code that relies on that option.
 *
 * @since 1.3.0
 *
 * @return string The Gmail OAuth auth URL or an empty string on error.
 */
if ( ! function_exists( 'post_smtp_get_gmail_auth_url' ) ) :
	function post_smtp_get_gmail_auth_url() {
		// Define the redirect URL for the OAuth flow.
		$redirect_url = admin_url( 'admin.php?socket=gmail_api&step=2' );

		// Generate nonce for CSRF protection (required by security report).
		$nonce = wp_create_nonce( 'gmail_oauth_redirect' );

		// API endpoint to fetch the OAuth URL.
		$api_url = 'https://connect.postmansmtp.com/wp-json/gmail-oauth/v1/auth-url';

		// Make the remote API request.
		$response = wp_remote_get(
			add_query_arg(
				array(
					'client_site_url' => urlencode( $redirect_url ),
					'nonce'           => $nonce,
				),
				$api_url
			)
		);

		// Check for errors in the API request.
		if ( is_wp_error( $response ) ) {
			return '';
		}

		// Decode the API response.
		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		// Check if the response contains the expected OAuth URL.
		if ( empty( $data['auth_url'] ) ) {
			return '';
		}

		$auth_url = esc_url_raw( $data['auth_url'] );

		// Store the OAuth URL in the WordPress options table for backwards compatibility.
		update_option( 'post_smtp_gmail_auth_url', $auth_url );

		return $auth_url;
	}
endif;

/**
 * Returns a fresh Office OAuth "auth_url" from the Post SMTP connect API.
 *
 * This helper generates a new nonce and passes it to the remote endpoint, which
 * bakes the nonce into the redirect URL. That nonce is then verified in
 * `handle_office365_oauth_redirect()` when Office365 redirects back.
 *
 * The returned URL is also stored in the `post_smtp_office365_auth_url` option for
 * backward compatibility with any existing code that relies on that option.
 *
 * @since 1.3.0
 *
 * @return string The Office OAuth auth URL or an empty string on error.
 */
if ( ! function_exists( 'post_smtp_get_office365_auth_url' ) ) :
	function post_smtp_get_office365_auth_url() {
		// Define the redirect URL for the OAuth flow.
		$redirect_url = admin_url( 'admin.php?socket=office365_api&step=2&page=postman%2Fconfiguration_wizard' );

		// Generate nonce for CSRF protection (required by security report).
		$nonce = wp_create_nonce( 'office365_oauth_redirect' );

		// API endpoint to fetch the OAuth URL.
		$api_url = 'https://connect2.postmansmtp.com/wp-json/office365-oauth/v1/auth-url';

		// Make the remote API request.
		$response = wp_remote_get(
			add_query_arg(
				array(
					'client_site_url' => $redirect_url,
					'nonce'           => $nonce,
				),
				$api_url
			)
		);

		// Check for errors in the API request.
		if ( is_wp_error( $response ) ) {
			return '';
		}

		// Decode the API response.
		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		// Check if the response contains the expected OAuth URL.
		if ( empty( $data['auth_url'] ) ) {
			return '';
		}

		$auth_url = esc_url_raw( $data['auth_url'] );

		// Store the OAuth URL in the WordPress options table for backwards compatibility.
		update_option( 'post_smtp_office365_auth_url', $auth_url );

		return $auth_url;
	}
endif;

new PSP_Active_Deactivate();