<?php
/**
 * Advanced settings UI (modal) for Redirect After Login.
 *
 * @package RedirectAfterLogin
 */

namespace RedirectAfterLogin;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) ) {
	$module_id = 'redirect-after-login';
}
$defaults = Module::getDefaultSettings();

$raw      = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$settings = is_array( $raw ) ? array_merge( $defaults, $raw ) : $defaults;

$honor_redirect_to = ! empty( $settings['honor_redirect_to'] ) && $settings['honor_redirect_to'] !== '0';
$woocommerce_sync  = ! empty( $settings['woocommerce_sync'] ) && $settings['woocommerce_sync'] !== '0';
$fallback_url      = isset( $settings['fallback_url'] ) ? (string) $settings['fallback_url'] : '';
$role_redirects    = isset( $settings['role_redirects'] ) && is_array( $settings['role_redirects'] ) ? $settings['role_redirects'] : [];

if ( ! function_exists( 'wp_roles' ) ) {
	require_once ABSPATH . 'wp-admin/includes/user.php';
}

$all_roles = wp_roles()->roles;
uksort(
	$all_roles,
	static function ( $a, $b ) {
		$core = [ 'administrator' => 0, 'editor' => 1, 'author' => 2, 'contributor' => 3, 'subscriber' => 4 ];
		$ia   = $core[ $a ] ?? 100;
		$ib   = $core[ $b ] ?? 100;
		if ( $ia !== $ib ) {
			return $ia <=> $ib;
		}
		return strcasecmp( $a, $b );
	}
);

$wc_active = class_exists( 'WooCommerce' );

$per_role_unlocked = function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
$license_page_url  = admin_url( 'admin.php?page=powersuite-license' );

$enable_role_redirects = Module::isEnableRoleRedirectsEffective( is_array( $raw ) ? $raw : [], $settings );

$settings_for_rules = $settings;
$settings_for_rules['enable_role_redirects'] = $enable_role_redirects;
$has_actionable_rules = Module::hasActionableRedirectRules( $settings_for_rules );

?>

<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>" data-per-role-active="<?php echo $per_role_unlocked ? '1' : '0'; ?>">
	<p class="description">
		<?php esc_html_e( 'Set a fallback URL and/or per-role URLs (Premium) to control where users land after login. All destinations are validated on save and at login (same-site only; login page URLs are rejected). Honor redirect_to is enabled by default so deep links and reauth flows are preserved.', 'wp-powersuite' ); ?>
	</p>

	<div class="notice notice-warning inline wpps-ral-inactive-notice" style="margin: 0 0 16px; padding: 10px 12px;<?php echo $has_actionable_rules ? ' display:none;' : ''; ?>">
		<p style="margin:0;" class="wpps-ral-inactive-notice__default">
			<?php esc_html_e( 'No redirect rules are active yet. Add a Fallback URL and/or configure per-role URLs — Honor redirect_to and WooCommerce sync alone keep WordPress default destinations.', 'wp-powersuite' ); ?>
		</p>
		<p style="margin:0;" class="wpps-ral-inactive-notice__license" hidden>
			<?php esc_html_e( 'Per-role redirects are enabled but require an active Premium license. Add a Fallback URL below, or activate your license to use role URLs.', 'wp-powersuite' ); ?>
		</p>
		<p style="margin:0;" class="wpps-ral-inactive-notice__empty-roles" hidden>
			<?php esc_html_e( 'Per-role redirects are enabled but no role URLs are set yet. Add at least one role URL or a Fallback URL for this module to take effect.', 'wp-powersuite' ); ?>
		</p>
	</div>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>


		<table class="form-table" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'Honor redirect_to', 'wp-powersuite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: redirect_to', 'wp-powersuite' ),
							__( 'When the login flow includes a safe redirect_to target, send the user there first instead of fallback or per-role URLs.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<label>
							<input type="checkbox"
								class="wp-powersuite-advanced-setting"
								data-setting-key="honor_redirect_to"
								name="honor_redirect_to"
								value="1"
								<?php checked( $honor_redirect_to ); ?>
							/>
							<?php esc_html_e( 'When the login request includes a valid redirect_to (or WooCommerce redirect), send the user there before applying role or fallback rules.', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<?php if ( $wc_active ) : ?>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'WooCommerce', 'wp-powersuite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: WooCommerce redirect', 'wp-powersuite' ),
							__( 'Mirror the same redirect logic on My Account login via woocommerce_login_redirect.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<label>
							<input type="checkbox"
								class="wp-powersuite-advanced-setting"
								data-setting-key="woocommerce_sync"
								name="woocommerce_sync"
								value="1"
								<?php checked( $woocommerce_sync ); ?>
							/>
							<?php esc_html_e( 'Apply the same rules on the WooCommerce login form (woocommerce_login_redirect).', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<?php endif; ?>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_fallback_url' ); ?>"><?php esc_html_e( 'Fallback URL', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: fallback URL', 'wp-powersuite' ),
							__( 'Used when no per-role URL applies and redirect_to is off or missing. Must be same-site / allowed hosts.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<input type="text"
							class="regular-text wp-powersuite-advanced-setting"
							data-setting-key="fallback_url"
							name="fallback_url"
							id="<?php echo esc_attr( $module_id . '_fallback_url' ); ?>"
							value="<?php echo esc_attr( $fallback_url ); ?>"
							placeholder="<?php echo esc_attr( home_url( '/' ) ); ?>"
							autocomplete="off"
						/>
						<p class="description">
							<?php esc_html_e( 'Used when no per-role URL matches (and when “Honor redirect_to” is off or the request has no valid redirect). Login page URLs are not allowed. Leave empty to keep WordPress default behavior for that case.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-ral-enable-roles"><?php esc_html_e( 'Use per-role redirect URLs', 'wp-powersuite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: per-role redirects', 'wp-powersuite' ),
							__( 'Premium: send users to different URLs by role. Unchecked keeps saved URLs but does not apply them.', 'wp-powersuite' )
						);
						?>
					</th>
					<td>
						<label>
							<input type="checkbox"
								id="wpps-ral-enable-roles"
								class="wp-powersuite-advanced-setting"
								data-setting-key="enable_role_redirects"
								name="enable_role_redirects"
								value="1"
								<?php checked( $enable_role_redirects ); ?>
							/>
							<?php esc_html_e( 'When checked, the per-role table below is shown and used on login (Premium). When unchecked, saved per-role URLs are kept but not applied.', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>

		<div class="wpps-ral-role-master" style="margin-top:1.5em;">
			<div id="wpps-ral-role-panel" class="wpps-ral-role-panel" style="<?php echo $enable_role_redirects ? '' : 'display:none;'; ?>">

		<h3 class="title" style="margin-top:0;">
			<?php esc_html_e( 'Per-role URLs', 'wp-powersuite' ); ?>
			<?php
			wpps_render_modal_settings_tip(
				__( 'Help: role table', 'wp-powersuite' ),
				__( 'First matching role wins in administrator → subscriber order, then other roles alphabetically.', 'wp-powersuite' )
			);
			?>
			<?php if ( ! $per_role_unlocked ) : ?>
				<span class="wpps-pro-badge"><?php esc_html_e( 'Premium', 'wp-powersuite' ); ?></span>
			<?php endif; ?>
		</h3>
		<?php if ( ! $per_role_unlocked ) : ?>
			<div class="notice notice-info inline" style="margin: 8px 0 12px; padding: 8px 12px;">
				<p style="margin:0;">
					<?php
					echo wp_kses_post(
						sprintf(
							/* translators: %s: URL to license page */
							__( 'Per-role redirect URLs are a Premium feature. <a href="%s">Activate your license</a> to configure and use them. Free users can still use Fallback URL, Honor redirect_to, and WooCommerce sync.', 'wp-powersuite' ),
							esc_url( $license_page_url )
						)
					);
					?>
				</p>
			</div>
		<?php endif; ?>
		<p class="description">
			<?php esc_html_e( 'If a user has multiple roles, the first match wins using order: Administrator, Editor, Author, Contributor, Subscriber, then other roles A–Z.', 'wp-powersuite' ); ?>
		</p>

		<table class="widefat striped" style="max-width: 640px;<?php echo $per_role_unlocked ? '' : ' opacity: 0.92;'; ?>">
			<thead>
				<tr>
					<th scope="col"><?php esc_html_e( 'Role', 'wp-powersuite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'Redirect URL', 'wp-powersuite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $all_roles as $role_key => $role_def ) : ?>
					<?php
					$role_key   = sanitize_key( $role_key );
					$role_label = isset( $role_def['name'] ) ? translate_user_role( $role_def['name'] ) : $role_key;
					$url_val    = isset( $role_redirects[ $role_key ] ) ? (string) $role_redirects[ $role_key ] : '';
					?>
					<tr>
						<td>
							<strong><?php echo esc_html( $role_label ); ?></strong>
							<br><code style="font-size:11px;"><?php echo esc_html( $role_key ); ?></code>
						</td>
						<td>
							<?php if ( $per_role_unlocked ) : ?>
							<input type="text"
								class="large-text wpps-ral-role-url-input wp-powersuite-advanced-setting"
								data-setting-key="<?php echo esc_attr( 'role_redirects.' . $role_key ); ?>"
								name="<?php echo esc_attr( 'role_redirects[' . $role_key . ']' ); ?>"
								value="<?php echo esc_attr( $url_val ); ?>"
								placeholder="<?php echo esc_attr( __( 'Full URL or path, e.g. /my-account/', 'wp-powersuite' ) ); ?>"
								autocomplete="off"
							/>
							<?php else : ?>
							<input type="text"
								class="large-text"
								value="<?php echo esc_attr( $url_val ); ?>"
								placeholder="<?php echo esc_attr( __( 'Premium — activate license to edit', 'wp-powersuite' ) ); ?>"
								autocomplete="off"
								readonly
								disabled
								aria-readonly="true"
							/>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>

		<p class="description" style="margin-top:12px;">
			<?php
			echo esc_html(
				sprintf(
					/* translators: %1$s–%3$s: hook names */
					__( 'Developers: `%1$s` (return false to skip), `%2$s` (priority), `%3$s` (final URL). Social sign-in modules also run this filter chain after OAuth login.', 'wp-powersuite' ),
					'wp_powersuite_redirect_after_login_should_apply',
					'wp_powersuite_redirect_after_login_priority',
					'wp_powersuite_login_redirect_url'
				)
			);
			?>
		</p>

			</div>
		</div>
</form>
</div>

<script>
(function () {
	var root = document.querySelector('.wp-powersuite-module-settings[data-module-id="redirect-after-login"]');
	if (!root) {
		return;
	}
	var toggle = root.querySelector('#wpps-ral-enable-roles');
	var panel = root.querySelector('#wpps-ral-role-panel');
	var notice = root.querySelector('.wpps-ral-inactive-notice');
	var fallback = root.querySelector('#<?php echo esc_js( $module_id . '_fallback_url' ); ?>');
	var roleInputs = root.querySelectorAll('.wpps-ral-role-url-input');

	var hasRoleUrl = function () {
		for (var i = 0; i < roleInputs.length; i++) {
			if ((roleInputs[i].value || '').trim() !== '') {
				return true;
			}
		}
		return false;
	};

	var syncNotice = function () {
		if (!notice) {
			return;
		}
		var hasFallback = fallback && (fallback.value || '').trim() !== '';
		var rolesOn = toggle && toggle.checked;
		var perRoleActive = root.getAttribute('data-per-role-active') === '1';
		var active = hasFallback || (perRoleActive && rolesOn && hasRoleUrl());
		var msgDefault = notice.querySelector('.wpps-ral-inactive-notice__default');
		var msgLicense = notice.querySelector('.wpps-ral-inactive-notice__license');
		var msgEmptyRoles = notice.querySelector('.wpps-ral-inactive-notice__empty-roles');

		if (msgDefault) {
			msgDefault.hidden = false;
		}
		if (msgLicense) {
			msgLicense.hidden = true;
		}
		if (msgEmptyRoles) {
			msgEmptyRoles.hidden = true;
		}

		if (!active && rolesOn && !hasFallback) {
			if (!perRoleActive && msgLicense) {
				if (msgDefault) {
					msgDefault.hidden = true;
				}
				msgLicense.hidden = false;
			} else if (perRoleActive && !hasRoleUrl() && msgEmptyRoles) {
				if (msgDefault) {
					msgDefault.hidden = true;
				}
				msgEmptyRoles.hidden = false;
			}
		}

		notice.style.display = active ? 'none' : '';
	};

	var sync = function () {
		if (toggle && panel) {
			panel.style.display = toggle.checked ? '' : 'none';
		}
		syncNotice();
	};

	if (toggle) {
		toggle.addEventListener('change', sync);
	}
	if (fallback) {
		fallback.addEventListener('input', syncNotice);
	}
	roleInputs.forEach(function (input) {
		input.addEventListener('input', syncNotice);
	});
	sync();
})();
</script>
