<?php
/**
 * Amazon Authorization Controller
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/controllers/authorization
 * @author     miniOrange
 */

declare(strict_types=1);

namespace MOMCS_Sync\Includes\Common\Controllers\Authorization;

use MOMCS_Sync\Includes\Common\Constants\Plugin_Constants;
use MOMCS_Sync\Includes\Common\Handlers\Amazon_Auth_Handler;
use MOMCS_Sync\Includes\Common\Utils\Utils;

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

/**
 * Controller class for handling Amazon authorization.
 */
class Amazon_Auth_Controller {

	/**
	 * Handle the authorization request.
	 *
	 * @return void
	 */
	public static function handle_authorize_request() {
		// Check nonce.
		if ( ! current_user_can( 'manage_options' ) || ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'momcs_sync_authorize_nonce' ) ) {
			wp_send_json_error( array( 'message' => Plugin_Constants::MESSAGE_SECURITY_CHECK_FAILED ) );
		}

		// Store connection details in session for later use.
		$connection_name = ! empty( $_POST['connection_name'] ) ? sanitize_text_field( wp_unslash( $_POST['connection_name'] ) ) : '';
		$marketplace_id  = ! empty( $_POST['region'] ) ? sanitize_text_field( wp_unslash( $_POST['region'] ) ) : '';

		// Store in session.
		if ( ! session_id() ) {
			session_start();
		}

		$_SESSION['momcs_sync_connection_name'] = $connection_name;
		$_SESSION['momcs_sync_region']          = $marketplace_id;

		// Build broker authorize URL with WP callback.
		$auth_url     = rtrim( Plugin_Constants::BROKER_BASE_URL, '/' ) . Plugin_Constants::BROKER_AUTHORIZE_PATH . '?redirect_url=' . site_url();
		wp_send_json_success( array( 'auth_url' => $auth_url ) );
	}

	/**
	 * Handle the OAuth redirect on front-end via init hook.
	 * Expects `?momcs_amz_oauth=1&spapi_oauth_code=...&selling_partner_id=...`.
	 */
	public static function handle_oauth_callback() {
		$code      = Utils::get_current_page_parameter_value( 'spapi_oauth_code', '' );
		$seller_id = Utils::get_current_page_parameter_value( 'selling_partner_id', '' );

		if ( empty( $code ) || empty( $seller_id ) ) {
			return;
		}

		// Retrieve session context.
		if ( ! session_id() ) {
			session_start();
		}
		$connection_name = isset( $_SESSION['momcs_sync_connection_name'] ) ? sanitize_text_field( wp_unslash( $_SESSION['momcs_sync_connection_name'] ) ) : '';
		$marketplace_id  = isset( $_SESSION['momcs_sync_region'] ) ? sanitize_text_field( wp_unslash( $_SESSION['momcs_sync_region'] ) ) : '';
		if ( empty( $connection_name ) || empty( $marketplace_id ) ) {
			wp_die( esc_html( Plugin_Constants::MESSAGE_AUTHORIZATION_CONTEXT_NOT_FOUND ) );
		}

		// Delegate OAuth processing to handler.
		$channel_uuid = '';
		try {
			$channel_uuid = ( new Amazon_Auth_Handler() )->process_amazon_oauth_callback( $connection_name, $marketplace_id, $seller_id, $code );
		} catch ( \Throwable $e ) {
			wp_die( esc_html( Plugin_Constants::MESSAGE_AUTHORIZATION_FAILED_PERSIST . $e->getMessage() ) );
		}

		// Clear session context.
		unset( $_SESSION['momcs_sync_connection_name'], $_SESSION['momcs_sync_region'] );

		// Render only a script by enqueueing a tiny file and force-printing it.
		// Pass the new channel UUID so the popup can relay it to the parent window.
		header( 'Content-Type: text/html; charset=utf-8' );
		wp_register_script( 'momcs-oauth-close', MOMCS_PLUGIN_URL . 'assets/js/oauth-close.js', array(), MOMCS_VERSION, true );
		wp_localize_script(
			'momcs-oauth-close',
			'momcs_oauth_data',
			array( 'uuid' => $channel_uuid )
		);
		wp_print_scripts( 'momcs-oauth-close' );
		exit;
	}
}
