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

// Register admin menu
add_action('admin_menu', 'aramex_up_admin_menu');
function aramex_up_admin_menu() {
	add_menu_page(
		'eCommCore',
		'eCommCore',
		'manage_woocommerce',
		'ecommcore-login',
		'aramex_unified_login_form',
		esc_url(plugin_dir_url(__DIR__)) . 'assets/images/menu-icon.svg',
		3
	);
}

// Render Login Form.
function aramex_unified_login_form() {

	// Params for Auth redirect URL.
	$unique_identifier = get_option('aramex_unified_identifier');
	$store_name        = get_bloginfo('name');
	$store_base_url    = esc_url_raw(untrailingslashit(rest_url()));
	$plugin_key        = 'WOOCOM';

	// Final redirect URL
	$redirect_url = add_query_arg(
		[
			'store_name'      => $store_name,
			'store_base_url'  => $store_base_url,
			'plugin_store_id' => $unique_identifier,
			'plugin_key'      => $plugin_key,
		],
		ARXEC_UNIFIED_PORTAL_LOGIN_URL
	);

	// Handle continue button click.
	if (isset($_POST['login_submit']) && check_admin_referer('up_login_action', 'up_login_nonce')) {
		wp_redirect($redirect_url);
		exit;
	}
	// Check if token is already saved
	$loggedin_usertoken = get_option('aramex_unified_jwt_token');
	$btn_text = $loggedin_usertoken ? 'Connected' : 'Continue';
	?>
	
	<div id="login-box">
		<div class="form-section">
			<h1 style="font-size: 22px; margin-bottom: 20px;">Open eCommCore Portal</h1>
			<form action="" method="post" target="_blank">
				<?php wp_nonce_field('up_login_action', 'up_login_nonce'); ?>
				<div class="action" style="margin-bottom: 15px;">
					<button type="submit" id="aramex-continue-btn" class="button button-primary aramex-btn" name="login_submit">
						<span id="aramex-continue-text"><?php echo esc_html($btn_text); ?></span>
					</button>
				</div>
			</form>
		</div>
	</div>
	<?php
}
