<?php
/**
 * Email Reports - Settings modal content
 *
 * @var string $module_id
 */

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

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 ?? 'email-reports' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Email Reports requires an active license. Activate your license to schedule digest emails.', '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;
}

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

$module_id = $module_id ?? 'email-reports';
$settings = \EmailReports\Includes\ReportService::getSettings();
$registry = \EmailReports\Includes\ReportRegistry::getInstance();
$registry->init();
$sections = $registry->getSections( true );

$days = [
	0 => __( 'Sunday', 'wp-powersuite' ),
	1 => __( 'Monday', 'wp-powersuite' ),
	2 => __( 'Tuesday', 'wp-powersuite' ),
	3 => __( 'Wednesday', 'wp-powersuite' ),
	4 => __( 'Thursday', 'wp-powersuite' ),
	5 => __( 'Friday', 'wp-powersuite' ),
	6 => __( 'Saturday', 'wp-powersuite' ),
];
?>
<style>
.wpps-er-tabs { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 20px; align-items: flex-start; }
.wpps-er-tab-panels { flex: 1 1 100%; order: 10; }
.wpps-er-tab-btn { padding: 8px 16px; border: 1px solid #c3c4c7; background: #f6f7f7; border-radius: 4px; cursor: pointer; font-size: 13px; transition: background .15s, color .15s, border-color .15s; }
.wpps-er-tab-btn:hover { background: #fff; }
.wpps-er-tab-btn.is-active { background: #fff; border-color: #2271b1; color: #2271b1; }
.wpps-er-tab-panels { width: 100%; }
.wpps-er-tab-panel { display: none; padding: 20px 24px; background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; }
.wpps-er-tab-panel.is-active { display: block; }
.wpps-er-tab-panel .form-table { margin: 0; }
.wpps-er-tab-panel .form-table th { padding: 12px 10px 12px 0; width: 180px; vertical-align: top; }
.wpps-er-tab-panel .form-table td { padding: 12px 0; }
.wpps-er-tab-panel select,
.wpps-er-tab-panel input[type="text"],
.wpps-er-tab-panel input[type="time"],
.wpps-er-tab-panel input[type="url"] { min-width: 220px; width: 100%; max-width: 320px; box-sizing: border-box; }
.wpps-er-tab-panel .wpps-color-field-row { display: inline-flex; align-items: center; gap: 10px; flex-wrap: nowrap; }
.wpps-er-tab-panel .wpps-color-code-wrap .wpps-color-code-input { min-width: 0; width: 100px !important; max-width: 100px !important; }
.wpps-er-tab-panel .wpps-color-picker-circle { width: 40px !important; height: 40px !important; min-width: 40px; min-height: 40px; flex-shrink: 0; border-radius: 50% !important; border: 2px solid #ddd !important; padding: 0 !important; cursor: pointer; -webkit-appearance: none !important; -moz-appearance: none !important; appearance: none !important; overflow: hidden; }
.wpps-er-tab-panel .wpps-color-picker-circle::-webkit-color-swatch-wrapper { padding: 0 !important; margin: 0 !important; border: none !important; border-radius: 50% !important; }
.wpps-er-tab-panel .wpps-color-picker-circle::-webkit-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
.wpps-er-tab-panel .wpps-color-picker-circle::-moz-color-swatch { border: none !important; border-radius: 50% !important; width: 100% !important; height: 100% !important; }
.wpps-er-tab-panel .wpps-color-code-wrap { display: inline-block; position: relative; margin: 0; flex-shrink: 0; }
.wpps-er-tab-panel .wpps-color-code-wrap .wpps-color-reset { position: absolute; right: 5px; top: 50%; transform: translateY(-50%); padding: 0; margin: 0; background: none; border: none; cursor: pointer; color: #646970; }
.wpps-er-tab-panel .wpps-color-code-wrap .wpps-color-reset:hover { color: #2271b1; }
.wpps-er-tab-panel textarea.large-text { min-width: 220px; width: 100%; max-width: 320px; box-sizing: border-box; }
.wpps-er-footer-editor-wrap { width: 100%; max-width: 100%; }
.wpps-er-footer-editor-wrap .wp-editor-wrap { width: 100% !important; }
.wpps-er-footer-editor-wrap .wp-editor-container { border: 1px solid #8c8f94; border-radius: 4px; overflow: hidden; }
.wpps-er-actions-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 8px; }
.wpps-er-custom-recipients-wrap { margin-top: 8px; }
.wpps-er-section-title { margin: 0 0 8px; font-size: 14px; font-weight: 600; color: #1d2327; }
</style>
<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>" data-er-nonce="<?php echo esc_attr( wp_create_nonce( 'wpps_email_reports' ) ); ?>">
	<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' ); ?>

		<div class="wpps-er-tabs">
			<button type="button" class="wpps-er-tab-btn is-active" role="tab" aria-selected="true" aria-controls="wpps-er-panel-schedule" data-tab="schedule"><?php esc_html_e( 'Schedule', 'wp-powersuite' ); ?></button>
			<button type="button" class="wpps-er-tab-btn" role="tab" aria-selected="false" aria-controls="wpps-er-panel-report" data-tab="report"><?php esc_html_e( 'Report', 'wp-powersuite' ); ?></button>
			<button type="button" class="wpps-er-tab-btn" role="tab" aria-selected="false" aria-controls="wpps-er-panel-branding" data-tab="branding"><?php esc_html_e( 'Branding', 'wp-powersuite' ); ?></button>
			<div class="wpps-er-tab-panels">
				<!-- Schedule tab: Schedule + Recipients -->
				<div id="wpps-er-panel-schedule" class="wpps-er-tab-panel is-active" role="tabpanel">
					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row"><?php esc_html_e( 'Enable Reports', 'wp-powersuite' ); ?></th>
								<td>
									<label>
										<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[enabled]" value="1" class="wp-powersuite-advanced-setting" data-setting-key="enabled" <?php checked( ! empty( $settings['enabled'] ) ); ?> />
										<?php esc_html_e( 'Send scheduled email reports', 'wp-powersuite' ); ?>
									</label>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Frequency', 'wp-powersuite' ); ?></th>
								<td>
									<select name="<?php echo esc_attr( $module_id ); ?>[schedule]" id="wpps-er-schedule" class="wp-powersuite-advanced-setting" data-setting-key="schedule">
										<option value="daily" <?php selected( $settings['schedule'] ?? '', 'daily' ); ?>><?php esc_html_e( 'Daily', 'wp-powersuite' ); ?></option>
										<option value="weekly" <?php selected( $settings['schedule'] ?? '', 'weekly' ); ?>><?php esc_html_e( 'Weekly', 'wp-powersuite' ); ?></option>
										<option value="monthly" <?php selected( $settings['schedule'] ?? '', 'monthly' ); ?>><?php esc_html_e( 'Monthly', 'wp-powersuite' ); ?></option>
									</select>
								</td>
							</tr>
							<tr class="wpps-er-row-weekly" style="<?php echo ( $settings['schedule'] ?? '' ) !== 'weekly' ? 'display:none' : ''; ?>">
								<th scope="row"><?php esc_html_e( 'Day of Week', 'wp-powersuite' ); ?></th>
								<td>
									<select name="<?php echo esc_attr( $module_id ); ?>[day_of_week]" class="wp-powersuite-advanced-setting" data-setting-key="day_of_week">
										<?php foreach ( $days as $val => $label ) : ?>
											<option value="<?php echo esc_attr( (string) $val ); ?>" <?php selected( (int) ( $settings['day_of_week'] ?? 1 ), $val ); ?>><?php echo esc_html( $label ); ?></option>
										<?php endforeach; ?>
									</select>
								</td>
							</tr>
							<tr class="wpps-er-row-monthly" style="<?php echo ( $settings['schedule'] ?? '' ) !== 'monthly' ? 'display:none' : ''; ?>">
								<th scope="row"><?php esc_html_e( 'Day of Month', 'wp-powersuite' ); ?></th>
								<td>
									<select name="<?php echo esc_attr( $module_id ); ?>[day_of_month]" class="wp-powersuite-advanced-setting" data-setting-key="day_of_month">
										<?php for ( $d = 1; $d <= 28; $d++ ) : ?>
											<option value="<?php echo esc_attr( (string) $d ); ?>" <?php selected( (int) ( $settings['day_of_month'] ?? 1 ), $d ); ?>><?php echo esc_html( (string) $d ); ?></option>
										<?php endfor; ?>
									</select>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Time', 'wp-powersuite' ); ?></th>
								<td>
									<input type="time" name="<?php echo esc_attr( $module_id ); ?>[time]" value="<?php echo esc_attr( $settings['time'] ?? '09:00' ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="time" />
									<p class="description"><?php esc_html_e( 'Uses your site timezone.', 'wp-powersuite' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Subject Line', 'wp-powersuite' ); ?></th>
								<td>
									<input type="text" name="<?php echo esc_attr( $module_id ); ?>[subject_format]" value="<?php echo esc_attr( $settings['subject_format'] ?? '' ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="subject_format" placeholder="<?php echo esc_attr( __( '%1$s – Site Report (%2$s to %3$s)', 'wp-powersuite' ) ); ?>" />
									<p class="description"><?php esc_html_e( 'Use %1$s = company, %2$s = start date, %3$s = end date. Leave blank for default.', 'wp-powersuite' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Send to', 'wp-powersuite' ); ?></th>
								<td>
									<label style="display:block;margin-bottom:8px;"><input type="radio" name="<?php echo esc_attr( $module_id ); ?>[recipients_type]" value="admin" class="wp-powersuite-advanced-setting wpps-er-recipients-type" data-setting-key="recipients_type" <?php checked( ( $settings['recipients_type'] ?? 'admin' ), 'admin' ); ?> /> <?php esc_html_e( 'Admin email', 'wp-powersuite' ); ?> (<?php echo esc_html( get_option( 'admin_email' ) ); ?>)</label>
									<label style="display:block;margin-bottom:8px;"><input type="radio" name="<?php echo esc_attr( $module_id ); ?>[recipients_type]" value="custom" class="wp-powersuite-advanced-setting wpps-er-recipients-type" data-setting-key="recipients_type" <?php checked( ( $settings['recipients_type'] ?? '' ), 'custom' ); ?> /> <?php esc_html_e( 'Custom emails', 'wp-powersuite' ); ?></label>
									<div class="wpps-er-custom-recipients-wrap" style="<?php echo ( $settings['recipients_type'] ?? 'admin' ) !== 'custom' ? 'display:none;' : ''; ?>">
										<textarea name="<?php echo esc_attr( $module_id ); ?>[custom_recipients]" rows="3" class="large-text wp-powersuite-advanced-setting" data-setting-key="custom_recipients" placeholder="one@example.com&#10;two@example.com"><?php echo esc_textarea( $settings['custom_recipients'] ?? '' ); ?></textarea>
										<p class="description"><?php esc_html_e( 'One email per line.', 'wp-powersuite' ); ?></p>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>

				<!-- Report tab: Report Sections + Actions -->
				<div id="wpps-er-panel-report" class="wpps-er-tab-panel" role="tabpanel">
					<h4 class="wpps-er-section-title"><?php esc_html_e( 'Report Sections', 'wp-powersuite' ); ?></h4>
					<?php if ( ! empty( $sections ) ) : ?>
						<p class="description" style="margin:0 0 12px;"><?php esc_html_e( 'Include data from enabled modules.', 'wp-powersuite' ); ?></p>
						<?php foreach ( $sections as $id => $sec ) : ?>
							<label style="display:block;margin-bottom:8px;">
								<input type="checkbox" name="<?php echo esc_attr( $module_id ); ?>[sections][]" value="<?php echo esc_attr( $id ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="sections" <?php checked( in_array( $id, $settings['sections'] ?? [], true ) ); ?> <?php disabled( empty( $sec['available'] ) ); ?> />
								<?php echo esc_html( $sec['title'] ); ?>
								<?php if ( empty( $sec['available'] ) ) : ?><span style="color:#646970;font-size:12px;"> (<?php esc_html_e( 'module disabled', 'wp-powersuite' ); ?>)</span><?php endif; ?>
							</label>
						<?php endforeach; ?>
					<?php else : ?>
						<p class="description"><?php esc_html_e( 'Enable Track 404s, Limit Login Attempts, Activity Log, or Email Logs to see sections.', 'wp-powersuite' ); ?></p>
					<?php endif; ?>

					<h4 class="wpps-er-section-title" style="margin-top:24px;"><?php esc_html_e( 'Actions', 'wp-powersuite' ); ?></h4>
					<div class="wpps-er-actions-row">
						<button type="button" class="button wpps-er-send-test"><?php esc_html_e( 'Send Test', 'wp-powersuite' ); ?></button>
						<button type="button" class="button wpps-er-send-now"><?php esc_html_e( 'Send Now', 'wp-powersuite' ); ?></button>
					</div>
					<p class="description" style="margin-top:8px;"><?php esc_html_e( 'Send a test email or trigger a report immediately. Use Save Settings in the modal footer to save your configuration.', 'wp-powersuite' ); ?></p>
				</div>

				<!-- Branding tab -->
				<div id="wpps-er-panel-branding" class="wpps-er-tab-panel" role="tabpanel">
					<table class="form-table" role="presentation">
						<tbody>
							<tr>
								<th scope="row"><?php esc_html_e( 'Company Name', 'wp-powersuite' ); ?></th>
								<td>
									<input type="text" name="<?php echo esc_attr( $module_id ); ?>[company_name]" value="<?php echo esc_attr( $settings['company_name'] ?? '' ); ?>" class="regular-text wp-powersuite-advanced-setting" data-setting-key="company_name" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" />
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Logo', 'wp-powersuite' ); ?></th>
								<td>
									<input type="hidden" name="<?php echo esc_attr( $module_id ); ?>[logo_id]" id="wpps-er-logo-id" value="<?php echo esc_attr( (string) ( $settings['logo_id'] ?? 0 ) ); ?>" class="wp-powersuite-advanced-setting" data-setting-key="logo_id" />
									<div id="wpps-er-logo-preview" style="min-height:50px;margin-bottom:10px;display:flex;align-items:center;"><?php
										if ( ! empty( $settings['logo_id'] ) ) {
											echo wp_get_attachment_image( (int) $settings['logo_id'], 'thumbnail' );
										} else {
											echo '<span style="color:#646970;">' . esc_html__( 'No logo', 'wp-powersuite' ) . '</span>';
										}
									?></div>
									<button type="button" class="button wpps-er-select-logo"><?php esc_html_e( 'Select Logo', 'wp-powersuite' ); ?></button>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Primary Color', 'wp-powersuite' ); ?></th>
								<td>
									<?php
									$primary_color = $settings['primary_color'] ?? '#2271b1';
									$primary_color_val = preg_match( '/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/', $primary_color ) ? ( strlen( $primary_color ) > 7 ? substr( $primary_color, 0, 7 ) : $primary_color ) : '#2271b1';
									?>
									<div class="wpps-color-field-row">
										<input type="color" id="wpps-er-primary-color" name="<?php echo esc_attr( $module_id ); ?>[primary_color]" value="<?php echo esc_attr( $primary_color_val ); ?>" class="wp-powersuite-advanced-setting wpps-color-picker-circle" data-setting-key="primary_color" />
										<div class="wpps-color-code-wrap">
											<input type="text" class="wpps-color-code-input regular-text wp-powersuite-advanced-setting" data-setting-key="primary_color" data-color-input="wpps-er-primary-color" data-default-color="#2271b1" value="<?php echo esc_attr( preg_match( '/^#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}|[a-fA-F0-9]{8})$/', $primary_color ) ? $primary_color : '#2271b1' ); ?>" style="width: 100px; padding-right: 25px;" placeholder="#2271b1" maxlength="9" />
											<button type="button" class="wpps-color-reset button-link" data-default-color="#2271b1"><span class="dashicons dashicons-undo" style="font-size: 16px; width: 16px; height: 16px;"></span></button>
										</div>
									</div>
								</td>
							</tr>
							<tr>
								<th scope="row"><?php esc_html_e( 'Footer Text', 'wp-powersuite' ); ?></th>
								<td>
									<div class="wpps-er-footer-editor-wrap">
										<textarea id="<?php echo esc_attr( $module_id ); ?>_footer_text" name="<?php echo esc_attr( $module_id ); ?>[footer_text]" rows="8" class="large-text wp-powersuite-advanced-setting" data-setting-key="footer_text" style="width:100%;max-width:100%;min-height:220px;"><?php echo esc_textarea( $settings['footer_text'] ?? '' ); ?></textarea>
										<p class="description"><?php esc_html_e( 'HTML or plain text. Shown at the bottom of email reports.', 'wp-powersuite' ); ?></p>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</form>
</div>

<script>
(function() {
	var $ = jQuery;
	var mid = '<?php echo esc_js( $module_id ); ?>';
	var container = document.querySelector('.wp-powersuite-module-settings[data-module-id="' + mid + '"]');
	var ajaxUrl = (window.wpPowerSuite && window.wpPowerSuite.ajaxUrl) || (typeof ajaxurl !== 'undefined' ? ajaxurl : '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>');
	var erNonce = container ? container.getAttribute('data-er-nonce') : '';
	// Tab switching - use document delegation
	var footerEditorInitialized = false;
	$(document).on('click', '.wpps-er-tab-btn', function() {
		var $btn = $(this);
		if (!$btn.closest('[data-module-id="' + mid + '"]').length) return;
		var tabId = $btn.data('tab');
		var $tabs = $btn.closest('.wpps-er-tabs');
		$('.wpps-er-tab-btn', $tabs).removeClass('is-active').attr('aria-selected', 'false');
		$btn.addClass('is-active').attr('aria-selected', 'true');
		$('.wpps-er-tab-panel', $tabs).removeClass('is-active');
		$('#wpps-er-panel-' + tabId, $tabs).addClass('is-active');
		// Lazy-init footer WYSIWYG when Branding tab is shown (TinyMCE fails when container is hidden)
		if (tabId === 'branding' && !footerEditorInitialized && typeof wp !== 'undefined' && wp.editor && wp.editor.initialize) {
			var editorId = mid + '_footer_text';
			var ta = document.getElementById(editorId);
			if (ta && !document.getElementById(editorId + '_ifr')) {
				wp.editor.initialize(editorId, {
					textarea_name: mid + '[footer_text]',
					textarea_rows: 8,
					media_buttons: true,
					teeny: false,
					quicktags: true,
					tinymce: { toolbar1: 'formatselect,bold,italic,underline,bullist,numlist,blockquote,link,unlink,forecolor,removeformat' }
				});
				footerEditorInitialized = true;
			}
		}
	});
	// Recipients type toggle - use document delegation
	$(document).on('change', '.wpps-er-recipients-type', function() {
		var $wrap = $(this).closest('[data-module-id="' + mid + '"]').find('.wpps-er-custom-recipients-wrap');
		$wrap.toggle($(this).val() === 'custom');
	});
	// Color reset - use document delegation (scoped to this module)
	$(document).on('click', '.wpps-color-reset', function(e) {
		if (!$(this).closest('[data-module-id="' + mid + '"]').length) return;
		e.preventDefault();
		var $btn = $(this);
		var def = $btn.data('default-color');
		var $textInput = $btn.prev('.wpps-color-code-input');
		var colorInputId = $textInput.data('color-input');
		var $colorInput = $('#' + colorInputId);
		$textInput.val(def);
		$colorInput.val(def);
		$textInput.trigger('change');
	});
	// Schedule row visibility - use document delegation
	$(document).on('change', '#wpps-er-schedule', function() {
		var $ctx = $(this).closest('[data-module-id="' + mid + '"]');
		if (!$ctx.length) return;
		var v = $(this).val();
		$('.wpps-er-row-weekly', $ctx).toggle(v === 'weekly');
		$('.wpps-er-row-monthly', $ctx).toggle(v === 'monthly');
	});
	if (typeof window.wpPowerSuite !== 'undefined') {
		window.wpPowerSuite.syncModuleSettingsBeforeSave = window.wpPowerSuite.syncModuleSettingsBeforeSave || {};
		window.wpPowerSuite.syncModuleSettingsBeforeSave[mid] = function() {
			if (typeof tinymce !== 'undefined') {
				var ed = tinymce.get(mid + '_footer_text');
				if (ed) ed.save();
			}
		};
	}
	// Logo picker - use document delegation
	var frame;
	$(document).on('click', '.wpps-er-select-logo', function(e) {
		var $ctx = $(this).closest('[data-module-id="' + mid + '"]');
		if (!$ctx.length) return;
		e.preventDefault();
		if (frame) { frame.open(); return; }
		frame = wp.media({ title: 'Select Logo', button: { text: 'Use' }, library: { type: 'image' }, multiple: false });
		frame.on('select', function() {
			var att = frame.state().get('selection').first().toJSON();
			$('#wpps-er-logo-id', $ctx).val(att.id);
			$('#wpps-er-logo-preview', $ctx).html(att.sizes && att.sizes.thumbnail ? $('<img>').attr('src', att.sizes.thumbnail.url) : $('<img>').attr('src', att.url));
		});
		frame.open();
	});
	$(document).on('click', '.wpps-er-send-test', function() {
		var $wrap = $(this).closest('.wp-powersuite-module-settings[data-module-id="' + mid + '"]');
		if (!$wrap.length) return;
		var n = $wrap.attr('data-er-nonce') || '';
		if (!n || !ajaxUrl) { alert('Configuration error. Please refresh the page.'); return; }
		var btn = $(this);
		btn.prop('disabled', true).text('Sending...');
		$.post(ajaxUrl, { action: 'wpps_email_reports_send_test', nonce: n })
			.done(function(r) { alert(r.success ? 'Test email sent!' : ((r.data && r.data.message) || 'Failed')); })
			.fail(function() { alert('Failed to send'); })
			.always(function() { btn.prop('disabled', false).text('Send Test'); });
	});
	$(document).on('click', '.wpps-er-send-now', function() {
		var $wrap = $(this).closest('.wp-powersuite-module-settings[data-module-id="' + mid + '"]');
		if (!$wrap.length) return;
		if (!confirm('Send report to all recipients now?')) return;
		var n = $wrap.attr('data-er-nonce') || '';
		if (!n || !ajaxUrl) { alert('Configuration error. Please refresh the page.'); return; }
		var btn = $(this);
		btn.prop('disabled', true).text('Sending...');
		$.post(ajaxUrl, { action: 'wpps_email_reports_send_now', nonce: n })
			.done(function(r) { alert(r.success ? 'Report sent!' : ((r.data && r.data.message) || 'Failed')); })
			.fail(function() { alert('Failed to send'); })
			.always(function() { btn.prop('disabled', false).text('Send Now'); });
	});
})();
</script>
