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

namespace RedirectAfterLogin;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

require_once __DIR__ . '/FeatureGate.php';

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'] : [];

$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 = FeatureGate::isPremiumLicensed();
$overlay_locked    = ! $per_role_unlocked;

$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'; ?>" data-overlay-locked="<?php echo $overlay_locked ? '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.', 'wppowersuite-lite' ); ?>
	</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.', 'wppowersuite-lite' ); ?>
		</p>
		<p style="margin:0;" class="wpps-ral-inactive-notice__license" hidden>
			<?php
			echo esc_html(
				function_exists( 'wp_powersuite_can_activate_license' ) && wp_powersuite_can_activate_license()
					? __( 'Per-role redirects are enabled but require an active Premium license. Add a Fallback URL below, or activate your license to use role URLs.', 'wppowersuite-lite' )
					: __( 'Per-role redirects are a Pro feature. Add a Fallback URL below, or get WP PowerSuite Pro to use role URLs.', 'wppowersuite-lite' )
			);
			?>
		</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.', 'wppowersuite-lite' ); ?>
		</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', 'wppowersuite-lite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: redirect_to', 'wppowersuite-lite' ),
							__( 'When the login flow includes a safe redirect_to target, send the user there first instead of fallback or per-role URLs.', 'wppowersuite-lite' )
						);
						?>
					</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.', 'wppowersuite-lite' ); ?>
						</label>
					</td>
				</tr>
				<?php if ( $wc_active ) : ?>
				<tr>
					<th scope="row">
						<?php esc_html_e( 'WooCommerce', 'wppowersuite-lite' ); ?>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: WooCommerce redirect', 'wppowersuite-lite' ),
							__( 'Mirror the same redirect logic on My Account login via woocommerce_login_redirect.', 'wppowersuite-lite' )
						);
						?>
					</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).', 'wppowersuite-lite' ); ?>
						</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', 'wppowersuite-lite' ); ?></label>
						<?php
						wpps_render_modal_settings_tip(
							__( 'Help: fallback URL', 'wppowersuite-lite' ),
							__( 'Used when no per-role URL applies and redirect_to is off or missing. Must be same-site / allowed hosts.', 'wppowersuite-lite' )
						);
						?>
					</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.', 'wppowersuite-lite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="wpps-ral-enable-roles"><?php esc_html_e( 'Use per-role redirect URLs', 'wppowersuite-lite' ); ?></label>
						<?php
						if ( $overlay_locked && function_exists( 'wpps_render_premium_badge' ) ) {
							wpps_render_premium_badge();
						}
						wpps_render_modal_settings_tip(
							__( 'Help: per-role redirects', 'wppowersuite-lite' ),
							__( 'Premium: send users to different URLs by role. Unchecked keeps saved URLs but does not apply them.', 'wppowersuite-lite' )
						);
						?>
					</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 disabled( $overlay_locked ); ?>
							/>
							<?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.', 'wppowersuite-lite' ); ?>
						</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 || $overlay_locked ) ? '' : 'display:none;'; ?>">

		<h3 class="title" style="margin-top:0;">
			<?php esc_html_e( 'Per-role URLs', 'wppowersuite-lite' ); ?>
			<?php
			if ( $overlay_locked && function_exists( 'wpps_render_premium_badge' ) ) {
				wpps_render_premium_badge();
			}
			wpps_render_modal_settings_tip(
				__( 'Help: role table', 'wppowersuite-lite' ),
				__( 'First matching role wins in administrator → subscriber order, then other roles alphabetically.', 'wppowersuite-lite' )
			);
			?>
		</h3>
		<?php
		if ( $overlay_locked && function_exists( 'wpps_render_premium_upsell_notice' ) ) {
			wpps_render_premium_upsell_notice();
		}
		?>
		<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.', 'wppowersuite-lite' ); ?>
		</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', 'wppowersuite-lite' ); ?></th>
					<th scope="col"><?php esc_html_e( 'Redirect URL', 'wppowersuite-lite' ); ?></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/', 'wppowersuite-lite' ) ); ?>"
								autocomplete="off"
							/>
							<?php else : ?>
							<input type="text"
								class="large-text"
								value="<?php echo esc_attr( $url_val ); ?>"
								placeholder="<?php echo esc_attr( __( 'Premium — unlock with WP PowerSuite Pro', 'wppowersuite-lite' ) ); ?>"
								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.', 'wppowersuite-lite' ),
					'wp_powersuite_redirect_after_login_should_apply',
					'wp_powersuite_redirect_after_login_priority',
					'wp_powersuite_login_redirect_url'
				)
			);
			?>
		</p>

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

<?php ob_start(); ?>
(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 overlayLocked = root.getAttribute('data-overlay-locked') === '1';
	var sync = function () {
		if (toggle && panel) {
			panel.style.display = (overlayLocked || 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();
})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-redirect-after-login-admin-php-script-1', (string) ob_get_clean() ); ?>
