<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use LoginEmailNotification\Module;
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'login-email-notification' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Admin Login Alerts requires an active license. Activate your license to configure login notifications.', 'wp-powersuite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wp-powersuite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'login-email-notification';
}

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}

if ( ! class_exists( Module::class, false ) && defined( 'WP_POWERSUITE_MODULES_DIR' ) ) {
	$mod = WP_POWERSUITE_MODULES_DIR . 'login-email-notification' . DIRECTORY_SEPARATOR . 'module.php';
	if ( is_readable( $mod ) ) {
		require_once $mod;
	}
}

$settings = class_exists( Module::class ) ? Module::normalizeSettings( $settings ) : $settings;

$geo_lookup_enabled      = ! empty( $settings['geo_lookup_enabled'] );
$include_user_agent      = ! empty( $settings['include_user_agent'] );
$notify_alternate_logins = ! empty( $settings['notify_alternate_logins'] );
$strict_login_detection  = ! empty( $settings['strict_login_detection'] );
$throttle_minutes        = (int) ( $settings['throttle_minutes'] ?? 5 );
$ip_header               = (string) ( $settings['ip_header'] ?? '' );

/**
 * @param array<string, mixed> $settings
 */
$aln_chk = static function ( string $key, string $label, array $settings ) : void {
	$on = ! empty( $settings[ $key ] );
	?>
	<label class="wpps-al-check">
		<input type="checkbox"
			name="<?php echo esc_attr( $key ); ?>"
			class="wp-powersuite-advanced-setting"
			data-setting-key="<?php echo esc_attr( $key ); ?>"
			value="1"
			<?php checked( $on ); ?>
		/>
		<span class="wpps-al-check__text"><?php echo esc_html( $label ); ?></span>
	</label>
	<?php
};

?>

<div class="wp-powersuite-module-settings wpps-al-modal-settings wpps-aln-modal-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="wpps-al-modal-lead description">
		<?php esc_html_e( 'Email alerts when someone with administrator access (manage_options) signs in. Password logins, custom login URLs, and PowerSuite 2FA are covered by default.', 'wp-powersuite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">

		<div class="wpps-al-modal-sheet" role="group" aria-label="<?php esc_attr_e( 'Login notification settings', 'wp-powersuite' ); ?>">

			<section class="wpps-al-modal-section" aria-labelledby="wpps-aln-heading-recipients">
				<h3 class="wpps-al-modal-section__title" id="wpps-aln-heading-recipients">
					<?php esc_html_e( 'Recipients', 'wp-powersuite' ); ?>
					<?php
					wpps_render_modal_settings_tip(
						__( 'Help: email recipients', 'wp-powersuite' ),
						__( 'Separate multiple addresses with commas. Each mailbox receives one message per qualifying login.', 'wp-powersuite' )
					);
					?>
				</h3>

				<div class="wpps-aln-field">
					<label class="wpps-aln-field-label" for="<?php echo esc_attr( $module_id ); ?>_emails"><?php esc_html_e( 'Email addresses', 'wp-powersuite' ); ?></label>
					<input
						type="text"
						id="<?php echo esc_attr( $module_id ); ?>_emails"
						name="emails"
						class="wpps-aln-input large-text wp-powersuite-advanced-setting"
						data-setting-key="emails"
						value="<?php echo esc_attr( $settings['emails'] ); ?>"
						autocomplete="email"
						inputmode="email"
						placeholder="<?php esc_attr_e( 'admin@example.com, ops@example.com', 'wp-powersuite' ); ?>"
					/>
					<p class="description wpps-aln-field-note"><?php esc_html_e( 'Invalid addresses are removed when you save.', 'wp-powersuite' ); ?></p>
				</div>

				<div class="wpps-aln-test-panel" aria-labelledby="wpps-aln-heading-test">
					<p class="wpps-aln-test-panel__title" id="wpps-aln-heading-test"><?php esc_html_e( 'Test delivery', 'wp-powersuite' ); ?></p>
					<div class="wpps-aln-test-panel__row">
						<input
							type="email"
							id="<?php echo esc_attr( $module_id ); ?>_test_email"
							class="wpps-aln-input"
							value="<?php echo esc_attr( wp_get_current_user()->user_email ); ?>"
							placeholder="<?php esc_attr_e( 'you@example.com', 'wp-powersuite' ); ?>"
							aria-label="<?php esc_attr_e( 'Test email address', 'wp-powersuite' ); ?>"
						/>
						<button type="button" class="button button-secondary" id="<?php echo esc_attr( $module_id ); ?>_test_btn">
							<?php esc_html_e( 'Send test email', 'wp-powersuite' ); ?>
						</button>
					</div>
					<p class="description wpps-aln-field-note"><?php esc_html_e( 'Save recipients first. The sample uses your account as the login example.', 'wp-powersuite' ); ?></p>
					<div class="wpps-aln-test-feedback" id="<?php echo esc_attr( $module_id ); ?>_test_feedback" role="status" aria-live="polite" hidden></div>
				</div>
			</section>

			<section class="wpps-al-modal-section" aria-labelledby="wpps-aln-heading-ip">
				<h3 class="wpps-al-modal-section__title" id="wpps-aln-heading-ip">
					<?php esc_html_e( 'Quiet logins', 'wp-powersuite' ); ?>
					<?php
					wpps_render_modal_settings_tip(
						__( 'Help: quiet IPs', 'wp-powersuite' ),
						__( 'One entry per line or comma-separated. Asterisks are allowed once per octet cluster (example: 10.0.0.*).', 'wp-powersuite' )
					);
					?>
				</h3>

				<div class="wpps-aln-field">
					<label class="wpps-aln-field-label" for="<?php echo esc_attr( $module_id ); ?>_exclude_ips"><?php esc_html_e( 'Never mail for these IPs', 'wp-powersuite' ); ?></label>
					<textarea
						id="<?php echo esc_attr( $module_id ); ?>_exclude_ips"
						name="exclude_ips"
						class="wpps-aln-textarea large-text wp-powersuite-advanced-setting"
						data-setting-key="exclude_ips"
						rows="4"
						spellcheck="false"
						placeholder="<?php esc_attr_e( "192.168.1.10\n203.0.113.*", 'wp-powersuite' ); ?>"
					><?php echo esc_textarea( $settings['exclude_ips'] ); ?></textarea>
				</div>

				<div class="wpps-aln-field wpps-aln-field--spaced">
					<label class="wpps-aln-field-label" for="<?php echo esc_attr( $module_id ); ?>_ip_header"><?php esc_html_e( 'Custom IP header (optional)', 'wp-powersuite' ); ?></label>
					<input
						type="text"
						id="<?php echo esc_attr( $module_id ); ?>_ip_header"
						name="ip_header"
						class="wpps-aln-input large-text wp-powersuite-advanced-setting"
						data-setting-key="ip_header"
						value="<?php echo esc_attr( $ip_header ); ?>"
						placeholder="<?php esc_attr_e( 'HTTP_X_REAL_IP', 'wp-powersuite' ); ?>"
					/>
					<p class="description wpps-aln-field-note"><?php esc_html_e( 'Defaults to Cloudflare CF-Connecting-IP when present, otherwise REMOTE_ADDR. Spoofable headers like X-Forwarded-For are blocked.', 'wp-powersuite' ); ?></p>
				</div>
			</section>

			<section class="wpps-al-modal-section" aria-labelledby="wpps-aln-heading-content">
				<h3 class="wpps-al-modal-section__title" id="wpps-aln-heading-content">
					<?php esc_html_e( 'Email content', 'wp-powersuite' ); ?>
				</h3>
				<div class="wpps-al-check-grid">
					<?php $aln_chk( 'include_user_agent', __( 'Include browser / device hint', 'wp-powersuite' ), $settings ); ?>
					<?php $aln_chk( 'geo_lookup_enabled', __( 'Approximate location lookup (ipwho.is)', 'wp-powersuite' ), $settings ); ?>
					<p class="description wpps-al-check-note"><?php esc_html_e( 'Geolocation sends visitor IPs to a third-party service when enabled.', 'wp-powersuite' ); ?></p>
				</div>
				<p class="wpps-aln-callout">
					<?php esc_html_e( 'Emails include username, role, time, IP, and optional location or browser data. Passwords, cookies, and session tokens are never included.', 'wp-powersuite' ); ?>
				</p>
			</section>

			<section class="wpps-al-modal-section wpps-al-modal-section--retention" aria-labelledby="wpps-aln-heading-detection">
				<h3 class="wpps-al-modal-section__title" id="wpps-aln-heading-detection">
					<?php esc_html_e( 'Detection', 'wp-powersuite' ); ?>
				</h3>
				<div class="wpps-al-check-grid">
					<?php $aln_chk( 'notify_alternate_logins', __( 'Magic links, OAuth, and temporary logins', 'wp-powersuite' ), $settings ); ?>
					<?php $aln_chk( 'strict_login_detection', __( 'Strict password-login only (ignore non–wp-admin redirects)', 'wp-powersuite' ), $settings ); ?>
				</div>
				<div class="wpps-al-retention-row wpps-aln-retention-row">
					<label class="wpps-al-retention-days" for="<?php echo esc_attr( $module_id ); ?>_throttle_minutes">
						<?php esc_html_e( 'Cooldown (minutes)', 'wp-powersuite' ); ?>
						<input
							type="number"
							id="<?php echo esc_attr( $module_id ); ?>_throttle_minutes"
							name="throttle_minutes"
							class="wp-powersuite-advanced-setting small-text"
							data-setting-key="throttle_minutes"
							min="0"
							max="60"
							step="1"
							value="<?php echo esc_attr( (string) $throttle_minutes ); ?>"
						/>
					</label>
					<p class="description wpps-aln-field-note wpps-aln-field-note--inline"><?php esc_html_e( 'Per user and IP. Use 0 for no cooldown.', 'wp-powersuite' ); ?></p>
				</div>
			</section>
		</div>

	</form>
</div>
<script>
(function() {
	var btn = document.getElementById('<?php echo esc_js( $module_id ); ?>_test_btn');
	if (!btn) return;

	var emailInput = document.getElementById('<?php echo esc_js( $module_id ); ?>_test_email');
	var feedback = document.getElementById('<?php echo esc_js( $module_id ); ?>_test_feedback');
	var nonce = window.wpPowerSuite && window.wpPowerSuite.nonce ? window.wpPowerSuite.nonce : '';

	btn.addEventListener('click', function() {
		if (!emailInput || !feedback) return;
		var testEmail = (emailInput.value || '').trim();
		if (!testEmail || testEmail.indexOf('@') === -1) {
			feedback.hidden = false;
			feedback.className = 'wpps-aln-test-feedback is-error';
			feedback.textContent = <?php echo wp_json_encode( __( 'Enter a valid email address.', 'wp-powersuite' ) ); ?>;
			return;
		}

		btn.disabled = true;
		feedback.hidden = false;
		feedback.className = 'wpps-aln-test-feedback is-pending';
		feedback.textContent = <?php echo wp_json_encode( __( 'Sending…', 'wp-powersuite' ) ); ?>;

		var data = new FormData();
		data.append('action', 'wp_powersuite_aln_test_email');
		data.append('nonce', nonce);
		data.append('test_email', testEmail);

		fetch(window.wpPowerSuite && window.wpPowerSuite.ajaxUrl ? window.wpPowerSuite.ajaxUrl : ajaxurl, {
			method: 'POST',
			body: data,
			credentials: 'same-origin'
		})
			.then(function(r) { return r.json(); })
			.then(function(res) {
				btn.disabled = false;
				if (res && res.success) {
					feedback.className = 'wpps-aln-test-feedback is-success';
					feedback.textContent = res.data && res.data.message ? res.data.message : <?php echo wp_json_encode( __( 'Test email sent.', 'wp-powersuite' ) ); ?>;
				} else {
					feedback.className = 'wpps-aln-test-feedback is-error';
					feedback.textContent = res && res.data && res.data.message ? res.data.message : <?php echo wp_json_encode( __( 'Failed to send test email.', 'wp-powersuite' ) ); ?>;
				}
			})
			.catch(function() {
				btn.disabled = false;
				feedback.className = 'wpps-aln-test-feedback is-error';
				feedback.textContent = <?php echo wp_json_encode( __( 'Failed to send test email.', 'wp-powersuite' ) ); ?>;
			});
	});
})();
</script>
