<?php
/**
 * Admin initializer.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Core\Admin;

use PrimeLink\Core\Ajax\ImportAjax;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

final class Admin {

    public static function init() {
        if ( ! is_admin() ) {
            return;
        }

        // Register AJAX handlers
        ImportAjax::register();

        Menu::register();
        Assets::register();
        ActivationWizard::init();
        \PrimeLink\Core\Admin\DashboardWidgets::register();
        
        // Handle Google Drive OAuth callback via admin_init (like integrate-google-drive)
        add_action( 'admin_init', array( __CLASS__, 'handle_gdrive_oauth_callback' ) );
        
        // Handle OneDrive OAuth callback via admin_init
        add_action( 'admin_init', array( __CLASS__, 'handle_onedrive_oauth_callback' ) );

        do_action( 'mt_primelink_admin_init' );
    }
    
    /**
     * Handle Google Drive OAuth callback via admin_init hook.
     * This is more reliable than REST API endpoint for OAuth callbacks.
     */
    public static function handle_gdrive_oauth_callback() {
        // Check if this is the OAuth callback
        if ( ! isset( $_GET['mt_primelink_gdrive_auth'] ) || 'callback' !== sanitize_key( $_GET['mt_primelink_gdrive_auth'] ) ) {
            return;
        }
        
        // Verify user is logged in
        if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You must be logged in to complete OAuth authentication.', 'primelink' ), esc_html__( 'Authentication Error', 'primelink' ), array( 'response' => 403 ) );
        }
        
        // Process the callback
        \PrimeLink\Core\Rest\ImportRest::gdrive_oauth_callback_admin();
    }
    
    /**
     * Handle OneDrive OAuth callback via admin_init hook.
     * This is more reliable than REST API endpoint for OAuth callbacks.
     * Supports both popup and full page redirects.
     * 
     * Detects OAuth callback by checking for 'code' parameter (Azure AD adds this automatically).
     */
    public static function handle_onedrive_oauth_callback() {
        // Detect OAuth callback by checking for 'code' parameter (Azure AD adds this)
        // Also check for our custom parameter as fallback
        $has_code = isset( $_GET['code'] ) && isset( $_GET['state'] );
        $has_custom_param = isset( $_GET['mt_primelink_onedrive_auth'] ) && 'callback' === sanitize_key( $_GET['mt_primelink_onedrive_auth'] );
        
        if ( ! $has_code && ! $has_custom_param ) {
            return;
        }
        
        // Verify user is logged in
        if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'You must be logged in to complete OAuth authentication.', 'primelink' ), esc_html__( 'Authentication Error', 'primelink' ), array( 'response' => 403 ) );
        }
        
        // Check if this is a popup callback
        $is_popup = isset( $_GET['popup'] ) && 'true' === sanitize_key( $_GET['popup'] );
        
        // Process the callback
        $result = \PrimeLink\Core\Rest\ImportRest::onedrive_oauth_callback_admin( $is_popup );
        
        // If popup, close window and notify parent
        if ( $is_popup ) {
            ?>
            <!DOCTYPE html>
            <html>
            <head>
                <title><?php esc_html_e( 'OneDrive Authentication', 'primelink' ); ?></title>
                <script>
                    // Close popup and notify parent window
                    if (window.opener) {
                        window.opener.postMessage({ type: 'onedrive_auth_success', message: 'Authentication successful' }, '*');
                        window.close();
                    } else {
                        // Fallback: redirect parent if opener not available
                        window.location.href = '<?php echo esc_url( admin_url( 'admin.php?page=mt-primelink-settings&tab=integrations&onedrive_auth=success' ) ); ?>';
                    }
                </script>
            </head>
            <body>
                <p><?php esc_html_e( 'Authentication successful! Closing window...', 'primelink' ); ?></p>
            </body>
            </html>
            <?php
            exit;
        }
    }
}