<?php

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

/**
 * Client-facing monthly report (Zap-style HTML email + print/PDF).
 */
final class IComm_SM_Report_Builder {

	/**
	 * Site domain without www (for report header).
	 */
	private static function report_domain(): string {
		$host = wp_parse_url(home_url('/'), PHP_URL_HOST);
		$domain = is_string($host) ? preg_replace('/^www\./i', '', $host) : '';
		return (string) $domain;
	}

	/**
	 * Hebrew month label, e.g. "יוני 2026".
	 */
	public static function hebrew_month_label(int $month, int $year): string {
		$names = [
			1 => 'ינואר',
			2 => 'פברואר',
			3 => 'מרץ',
			4 => 'אפריל',
			5 => 'מאי',
			6 => 'יוני',
			7 => 'יולי',
			8 => 'אוגוסט',
			9 => 'ספטמבר',
			10 => 'אוקטובר',
			11 => 'נובמבר',
			12 => 'דצמבר',
		];
		$name = $names[$month] ?? (string) $month;
		return $name . ' ' . $year;
	}

	/**
	 * Previous calendar month in site timezone (default for preview + auto send).
	 *
	 * @return array{start:string, end:string, label:string, domain:string, mode:string, month?:string}
	 */
	public static function previous_month_period(): array {
		$ts = current_time('timestamp');
		$ym = wp_date('Y-m', strtotime('first day of last month', $ts) ?: time());
		$period = self::month_period($ym);
		if ($period === null) {
			$start_ts = strtotime('first day of last month', $ts);
			$end_ts = strtotime('last day of last month', $ts);
			return [
				'start' => wp_date('Y-m-d', $start_ts ?: time()),
				'end' => wp_date('Y-m-d', $end_ts ?: time()),
				'label' => self::hebrew_month_label((int) wp_date('n', $start_ts ?: time()), (int) wp_date('Y', $start_ts ?: time())),
				'domain' => self::report_domain(),
				'mode' => 'month',
				'month' => wp_date('Y-m', $start_ts ?: time()),
			];
		}
		return $period;
	}

	/**
	 * Calendar month period from Y-m.
	 *
	 * @return array{start:string, end:string, label:string, domain:string, mode:string, month:string}|null
	 */
	public static function month_period(string $ym): ?array {
		$ym = trim($ym);
		if (!preg_match('/^(\d{4})-(\d{2})$/', $ym, $m)) {
			return null;
		}
		$year = (int) $m[1];
		$month = (int) $m[2];
		if ($year < 2000 || $year > 2100 || $month < 1 || $month > 12) {
			return null;
		}
		// Do not allow future months beyond current calendar month.
		$now_ym = wp_date('Y-m');
		if ($ym > $now_ym) {
			return null;
		}
		$start = sprintf('%04d-%02d-01', $year, $month);
		$dim = (int) date('t', strtotime($start . ' 12:00:00')); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
		if ($dim < 28) {
			return null;
		}
		$end = sprintf('%04d-%02d-%02d', $year, $month, $dim);
		return [
			'start' => $start,
			'end' => $end,
			'label' => self::hebrew_month_label($month, $year),
			'domain' => self::report_domain(),
			'mode' => 'month',
			'month' => sprintf('%04d-%02d', $year, $month),
		];
	}

	/**
	 * Free date range (inclusive), max 366 days.
	 *
	 * @return array{start:string, end:string, label:string, domain:string, mode:string}|null
	 */
	public static function custom_period(string $start, string $end): ?array {
		$start = IComm_SM_Dates::parse_to_ymd($start);
		$end = IComm_SM_Dates::parse_to_ymd($end);
		if ($start === '' || $end === '' || $start > $end) {
			return null;
		}
		$start_ts = strtotime($start . ' 12:00:00 UTC');
		$end_ts = strtotime($end . ' 12:00:00 UTC');
		if ($start_ts === false || $end_ts === false) {
			return null;
		}
		$days = (int) floor(($end_ts - $start_ts) / DAY_IN_SECONDS) + 1;
		if ($days < 1 || $days > 366) {
			return null;
		}
		$label = sprintf(
			/* translators: 1: start date, 2: end date */
			__('%1$s עד %2$s', 'icomm-metrix'),
			IComm_SM_Dates::format($start),
			IComm_SM_Dates::format($end)
		);
		return [
			'start' => $start,
			'end' => $end,
			'label' => $label,
			'domain' => self::report_domain(),
			'mode' => 'custom',
		];
	}

	/**
	 * Last N calendar months for the selector (newest first), including current month.
	 *
	 * @return array<int, array{value:string, label:string}>
	 */
	public static function list_month_options(int $count = 12): array {
		$count = max(1, min(24, $count));
		$out = [];
		$ts = current_time('timestamp');
		for ($i = 0; $i < $count; $i++) {
			$month_ts = strtotime(sprintf('first day of -%d month', $i), $ts);
			if ($month_ts === false) {
				continue;
			}
			$ym = wp_date('Y-m', $month_ts);
			$period = self::month_period($ym);
			if ($period === null) {
				continue;
			}
			$out[] = [
				'value' => $ym,
				'label' => (string) $period['label'],
			];
		}
		return $out;
	}

	/**
	 * Resolve period from GET/POST (report_mode, report_month, report_start, report_end).
	 *
	 * @param array<string, mixed> $src
	 * @return array{start:string, end:string, label:string, domain:string, mode:string, month?:string}
	 */
	public static function resolve_period_from_request(array $src): array {
		$mode = isset($src['report_mode']) ? sanitize_key((string) $src['report_mode']) : '';
		if ($mode === 'custom') {
			$start = isset($src['report_start']) ? sanitize_text_field((string) $src['report_start']) : '';
			$end = isset($src['report_end']) ? sanitize_text_field((string) $src['report_end']) : '';
			$custom = self::custom_period($start, $end);
			if ($custom !== null) {
				return $custom;
			}
		}
		if ($mode === 'month' || $mode === '') {
			$ym = isset($src['report_month']) ? sanitize_text_field((string) $src['report_month']) : '';
			if ($ym !== '') {
				$month = self::month_period($ym);
				if ($month !== null) {
					return $month;
				}
			}
		}
		return self::previous_month_period();
	}

	/**
	 * Query args to preserve the selected period across redirects / print.
	 *
	 * @param array<string, string> $period
	 * @return array<string, string>
	 */
	public static function period_query_args(array $period): array {
		$mode = (string) ($period['mode'] ?? 'month');
		if ($mode === 'custom') {
			return [
				'report_mode' => 'custom',
				'report_start' => (string) ($period['start'] ?? ''),
				'report_end' => (string) ($period['end'] ?? ''),
			];
		}
		$ym = (string) ($period['month'] ?? '');
		if ($ym === '' && !empty($period['start'])) {
			$ym = substr((string) $period['start'], 0, 7);
		}
		return [
			'report_mode' => 'month',
			'report_month' => $ym,
		];
	}

	/**
	 * Inclusive count of calendar months covered by a date range (min 1).
	 */
	public static function period_calendar_month_count(string $start, string $end): int {
		if (!preg_match('/^(\d{4})-(\d{2})-\d{2}$/', $start, $a) || !preg_match('/^(\d{4})-(\d{2})-\d{2}$/', $end, $b)) {
			return 1;
		}
		if ($start > $end) {
			return 1;
		}
		$y1 = (int) $a[1];
		$m1 = (int) $a[2];
		$y2 = (int) $b[1];
		$m2 = (int) $b[2];
		return max(1, (($y2 - $y1) * 12) + ($m2 - $m1) + 1);
	}

	/**
	 * Comparison window for KPI deltas.
	 *
	 * @param array<string, string> $period
	 * @return array{start:string, end:string, label:string}
	 */
	public static function comparison_period(array $period): array {
		$start = (string) ($period['start'] ?? '');
		$end = (string) ($period['end'] ?? '');
		$mode = (string) ($period['mode'] ?? 'month');
		$start_ts = strtotime($start . ' 12:00:00 UTC');
		$end_ts = strtotime($end . ' 12:00:00 UTC');
		if ($start_ts === false || $end_ts === false) {
			return ['start' => $start, 'end' => $end, 'label' => __('השוואה לחודש הקודם', 'icomm-metrix')];
		}

		if ($mode === 'month' || (!empty($period['month']) && preg_match('/^\d{4}-\d{2}$/', (string) $period['month']))) {
			$prev_start = gmdate('Y-m-d', strtotime('first day of last month', $start_ts) ?: $start_ts);
			$prev_end = gmdate('Y-m-d', strtotime('last day of last month', $start_ts) ?: $start_ts);
			return [
				'start' => $prev_start,
				'end' => $prev_end,
				'label' => __('השוואה לחודש הקודם', 'icomm-metrix'),
			];
		}

		$days = (int) floor(($end_ts - $start_ts) / DAY_IN_SECONDS) + 1;
		$prev_end_ts = $start_ts - DAY_IN_SECONDS;
		$prev_start_ts = $prev_end_ts - (($days - 1) * DAY_IN_SECONDS);
		return [
			'start' => gmdate('Y-m-d', $prev_start_ts),
			'end' => gmdate('Y-m-d', $prev_end_ts),
			'label' => __('השוואה לתקופה הקודמת באורך זהה', 'icomm-metrix'),
		];
	}

	/** Alias used by report page / print. */
	public static function preview_html(): string {
		return self::monthly_client_report_html();
	}

	/**
	 * Full monthly client report (cover + traffic + devices + keywords).
	 *
	 * @param array<string, string>|null $period
	 */
	public static function monthly_client_report_html($period = null): string {
		try {
			return self::build_monthly_client_report_html(is_array($period) ? $period : null);
		} catch (Throwable $e) {
			if (defined('WP_DEBUG') && WP_DEBUG && function_exists('error_log')) {
				error_log('icomm-metrix monthly report failed: ' . $e->getMessage());
			}
			return '<div dir="rtl" lang="he" style="font-family:Arial,sans-serif;padding:16px;">'
				. esc_html__('לא ניתן לבנות את הדוח כרגע. נסו לסנכרן נתונים שוב או לפתוח מחדש את המסך.', 'icomm-metrix')
				. '</div>';
		}
	}

	/**
	 * @param array<string, string>|null $period
	 */
	private static function build_monthly_client_report_html(?array $period = null): string {
		$period = is_array($period) ? $period : self::previous_month_period();
		$start = (string) ($period['start'] ?? '');
		$end = (string) ($period['end'] ?? '');
		$label = (string) ($period['label'] ?? '');
		$domain = (string) ($period['domain'] ?? '');
		if ($domain === '') {
			$domain = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		}

		$range_label = sprintf(
			__('%s עד %s', 'icomm-metrix'),
			IComm_SM_Dates::format($start),
			IComm_SM_Dates::format($end)
		);

		$summary = IComm_SM_DB::summary_between($start, $end);
		$compare = self::comparison_period($period);
		$prev = IComm_SM_DB::summary_between((string) $compare['start'], (string) $compare['end']);
		$compare_label = (string) ($compare['label'] ?? __('השוואה לחודש הקודם', 'icomm-metrix'));

		$channels = IComm_SM_Features::can_use('ga4_metrics')
			? IComm_SM_DB::ga4_breakdown('channel', $start, $end)
			: [];
		$devices = IComm_SM_Features::can_use('ga4_metrics')
			? IComm_SM_DB::ga4_breakdown('device', $start, $end)
			: [];
		// Up to 3 calendar months → weekly bars; longer ranges → monthly bars.
		$span_months = self::period_calendar_month_count($start, $end);
		$chart_by_week = $span_months <= 3;
		$series = $chart_by_week
			? IComm_SM_DB::weekly_series_between($start, $end)
			: IComm_SM_DB::monthly_series_between($start, $end);
		$top_queries = IComm_SM_DB::top_queries_between($start, $end, 20);
		$top_pages = IComm_SM_DB::top_pages_between($start, $end, 12);
		$query_pool = IComm_SM_DB::top_queries_between($start, $end, 80);

		$s = IComm_SM_Settings::get();
		$agency = '';
		$logo = '';
		if (IComm_SM_Features::can_use('report_branding')) {
			$agency = trim((string) ($s['agency_name'] ?? ''));
			$logo = esc_url((string) ($s['agency_logo_url'] ?? ''));
		}
		if ($agency === '') {
			$agency = 'icomm';
		}

		$watch = [];
		if (IComm_SM_Features::can_use('keyword_watch')) {
			$watch = array_values(array_filter(array_map('strval', (array) ($s['watch_keywords'] ?? []))));
		}
		$kw_weekly = $watch !== []
			? IComm_SM_DB::keywords_weekly_positions($watch, $start, $end)
			: ['weeks' => [], 'rows' => []];
		$kw_detail = [];
		if ($watch !== []) {
			$pool_by_q = [];
			foreach ($query_pool as $tq) {
				$q = (string) ($tq['query'] ?? '');
				if ($q !== '') {
					$pool_by_q[$q] = $tq;
				}
			}
			foreach ($watch as $wkw) {
				if (isset($pool_by_q[$wkw])) {
					$kw_detail[$wkw] = $pool_by_q[$wkw];
				}
			}
		}

		$ctr = ((int) $summary['impressions'] > 0)
			? round(((int) $summary['clicks'] / (int) $summary['impressions']) * 100, 2)
			: 0.0;

		$delta_pct = static function (float $cur, float $old): ?float {
			if ($old <= 0 && $cur <= 0) {
				return null;
			}
			if ($old <= 0) {
				return 100.0;
			}
			return round((($cur - $old) / $old) * 100, 1);
		};
		$fmt_delta = static function (?float $pct): string {
			if ($pct === null) {
				return '-';
			}
			$sign = $pct > 0 ? '+' : '';
			return $sign . number_format_i18n($pct, 1) . '%';
		};
		$delta_color = static function (?float $pct, bool $lower_is_better = false): string {
			if ($pct === null || abs($pct) < 0.05) {
				return '#1d2327';
			}
			$good = $lower_is_better ? ($pct < 0) : ($pct > 0);
			return $good ? '#00a32a' : '#d63638';
		};

		$d_clicks = $delta_pct((float) $summary['clicks'], (float) $prev['clicks']);
		$d_impr = $delta_pct((float) $summary['impressions'], (float) $prev['impressions']);
		$d_sess = $delta_pct((float) $summary['sessions'], (float) $prev['sessions']);
		$d_users = $delta_pct((float) $summary['users'], (float) $prev['users']);
		$d_pos = null;
		if ((float) $summary['avg_position'] > 0 && (float) $prev['avg_position'] > 0) {
			// Position: negative change (lower number) is improvement.
			$d_pos = round((float) $summary['avg_position'] - (float) $prev['avg_position'], 1);
		}

		$chan_sessions = 0;
		$chan_users = 0;
		$chan_bounce_w = 0.0;
		foreach ($channels as $c) {
			$chan_sessions += (int) $c['sessions'];
			$chan_users += (int) $c['users'];
			$chan_bounce_w += ((float) $c['bounce_rate']) * (int) $c['sessions'];
		}
		$chan_bounce_avg = $chan_sessions > 0 ? round($chan_bounce_w / $chan_sessions, 2) : 0.0;
		$dev_sessions = 0;
		foreach ($devices as $d) {
			$dev_sessions += (int) $d['sessions'];
		}

		$max_series_clicks = 1;
		$max_series_sess = 1;
		foreach ($series as $w) {
			$max_series_clicks = max($max_series_clicks, (int) ($w['clicks'] ?? 0));
			$max_series_sess = max($max_series_sess, (int) ($w['sessions'] ?? 0));
		}
		$chart_title = $chart_by_week
			? __('ביצועים לפי שבועות', 'icomm-metrix')
			: __('ביצועים לפי חודשים', 'icomm-metrix');
		$chart_col_label = $chart_by_week
			? __('שבוע', 'icomm-metrix')
			: __('חודש', 'icomm-metrix');

		$weeks = is_array($kw_weekly['weeks'] ?? null) ? $kw_weekly['weeks'] : [];
		$kw_has_weekly_data = false;
		foreach (($kw_weekly['rows'] ?? []) as $info) {
			if (!empty($info['start_pos']) || !empty($info['end_pos']) || !empty($info['avg'])) {
				$kw_has_weekly_data = true;
				break;
			}
			foreach (($info['weeks'] ?? []) as $v) {
				if ($v !== null) {
					$kw_has_weekly_data = true;
					break 2;
				}
			}
		}

		// Email-safe KPI card (Outlook ignores many CSS properties on bare divs).
		$card = static function (string $title, string $value, string $sub, string $sub_color): string {
			return '<td width="33%" valign="top" style="padding:6px;vertical-align:top;">'
				. '<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;">'
				. '<tr><td bgcolor="#f6f7f7" style="background-color:#f6f7f7;border:1px solid #dcdcde;border-radius:8px;padding:14px 12px;font-family:Arial,Helvetica,sans-serif;">'
				. '<p style="margin:0 0 6px;font-size:12px;color:#646970;font-family:Arial,Helvetica,sans-serif;">' . esc_html($title) . '</p>'
				. '<p style="margin:0;font-size:22px;font-weight:700;color:#1d2327;line-height:1.2;font-family:Arial,Helvetica,sans-serif;" dir="ltr">' . esc_html($value) . '</p>'
				. '<p style="margin:6px 0 0;font-size:12px;color:' . esc_attr($sub_color) . ';font-family:Arial,Helvetica,sans-serif;" dir="ltr">' . esc_html($sub) . '</p>'
				. '</td></tr></table></td>';
		};

		$chart_h = 100;
		$section_open = '<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;margin:0 0 18px;"><tr><td bgcolor="#ffffff" style="background-color:#ffffff;border:1px solid #dcdcde;border-radius:8px;padding:18px;font-family:Arial,Helvetica,sans-serif;">';
		$section_close = '</td></tr></table>';

		ob_start();
		?>
		<table role="presentation" class="icomm-sm-monthly-report" cellpadding="0" cellspacing="0" border="0" width="760" dir="rtl" lang="he" style="width:760px;max-width:760px;margin:0 auto;font-family:Arial,Helvetica,sans-serif;direction:rtl;text-align:right;color:#1d2327;line-height:1.45;">
		<tr><td style="padding:0;font-family:Arial,Helvetica,sans-serif;">

			<!-- Header: solid colors + accent strip (gradient as progressive enhancement) -->
			<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;margin:0 0 18px;">
				<tr>
					<td bgcolor="#0f172a" style="background-color:#0f172a;border-radius:8px;overflow:hidden;">
						<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;">
							<tr>
								<td bgcolor="#1e3a5f" style="padding:36px 28px 28px;background-color:#1e3a5f;background-image:linear-gradient(160deg,#0f172a 0%,#1e3a5f 55%,#2563eb 100%);text-align:right;direction:rtl;font-family:Arial,Helvetica,sans-serif;">
									<?php if ($logo !== '') : ?>
										<p style="margin:0 0 18px;"><img src="<?php echo esc_url($logo); ?>" alt="" style="max-height:52px;width:auto;background:#fff;padding:6px 10px;border-radius:4px;border:0;" /></p>
									<?php endif; ?>
									<p style="margin:0 0 8px;font-size:13px;letter-spacing:0.04em;color:#ffffff;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($agency); ?></p>
									<h1 style="margin:0 0 10px;font-size:28px;line-height:1.25;font-weight:700;color:#ffffff !important;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html(sprintf(__('דוח עבור %s', 'icomm-metrix'), $domain)); ?></h1>
									<p style="margin:0;font-size:20px;font-weight:600;color:#ffffff;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($label); ?></p>
									<p style="margin:18px 0 0;font-size:13px;color:#e0e7ff;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('דוח חודשי מפורט: תנועה, חיפוש אורגני, עמודים ומילות מפתח', 'icomm-metrix'); ?></p>
									<p style="margin:6px 0 0;font-size:12px;color:#c7d2fe;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($range_label); ?></p>
								</td>
							</tr>
							<tr>
								<td bgcolor="#2563eb" height="8" style="background-color:#2563eb;height:8px;font-size:0;line-height:8px;mso-line-height-rule:exactly;">&nbsp;</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>

			<!-- KPI -->
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 4px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('סיכום ביצועים', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($compare_label); ?></p>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;">
					<tr>
						<?php
						echo $card(__('כניסות לאתר', 'icomm-metrix'), number_format_i18n((int) $summary['sessions']), $fmt_delta($d_sess), $delta_color($d_sess)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $card(__('משתמשים', 'icomm-metrix'), number_format_i18n((int) $summary['users']), $fmt_delta($d_users), $delta_color($d_users)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $card(__('קליקים מגוגל', 'icomm-metrix'), number_format_i18n((int) $summary['clicks']), $fmt_delta($d_clicks), $delta_color($d_clicks)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						?>
					</tr>
					<tr>
						<?php
						echo $card(__('חשיפות בגוגל', 'icomm-metrix'), number_format_i18n((int) $summary['impressions']), $fmt_delta($d_impr), $delta_color($d_impr)); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						echo $card(__('CTR ממוצע', 'icomm-metrix'), number_format_i18n($ctr, 2) . '%', __('חיפוש אורגני', 'icomm-metrix'), '#646970'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						$pos_sub = $d_pos === null ? '-' : (($d_pos > 0 ? '+' : '') . number_format_i18n($d_pos, 1));
						$pos_col = ($d_pos === null) ? '#646970' : ($d_pos < 0 ? '#00a32a' : ($d_pos > 0 ? '#d63638' : '#1d2327'));
						echo $card(__('מיקום ממוצע', 'icomm-metrix'), (float) $summary['avg_position'] > 0 ? number_format_i18n((float) $summary['avg_position'], 1) : '-', $pos_sub, $pos_col); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
						?>
					</tr>
				</table>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

			<!-- Time series chart: weeks (≤3 months) or months (>3 months) -->
			<?php if ($series !== []) : ?>
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($chart_title); ?></h2>
				<p style="margin:0 0 12px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($range_label); ?></p>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;margin:0 0 10px;">
					<tr>
						<td bgcolor="#2563eb" width="12" height="12" style="width:12px;height:12px;background-color:#2563eb;font-size:0;line-height:12px;">&nbsp;</td>
						<td style="padding:0 8px 0 4px;font-size:12px;color:#646970;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></td>
						<td bgcolor="#f59e0b" width="12" height="12" style="width:12px;height:12px;background-color:#f59e0b;font-size:0;line-height:12px;">&nbsp;</td>
						<td style="padding:0 0 0 4px;font-size:12px;color:#646970;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('כניסות', 'icomm-metrix'); ?></td>
					</tr>
				</table>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;background:#fafafa;border:1px solid #dcdcde;">
					<tr>
						<td style="padding:16px 8px 12px;" align="center">
							<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" dir="rtl" style="margin:0 auto;border-collapse:collapse;direction:rtl;">
								<tr>
									<?php foreach ($series as $w) :
										$hc = max(4, (int) round(((int) $w['clicks'] / $max_series_clicks) * $chart_h));
										$hs = max(4, (int) round(((int) $w['sessions'] / $max_series_sess) * $chart_h));
										$pad_c = max(0, $chart_h - $hc);
										$pad_s = max(0, $chart_h - $hs);
										$bar_w = count($series) > 10 ? 12 : 16;
										?>
										<td valign="bottom" align="center" style="padding:0 6px 6px;vertical-align:bottom;">
											<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin:0 auto 6px;border-collapse:collapse;">
												<tr>
													<td valign="bottom" style="padding:0 2px;border-bottom:1px solid #dcdcde;">
														<?php echo self::email_vbar_html('#2563eb', $hc, $pad_c, $bar_w); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
													</td>
													<td valign="bottom" style="padding:0 2px;border-bottom:1px solid #dcdcde;">
														<?php echo self::email_vbar_html('#f59e0b', $hs, $pad_s, $bar_w); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
													</td>
												</tr>
											</table>
											<p style="margin:0 0 2px;font-size:11px;color:#646970;font-family:Arial,Helvetica,sans-serif;<?php echo $chart_by_week ? ' direction:ltr;' : ''; ?>"><?php echo esc_html((string) $w['label']); ?></p>
											<p style="margin:0;font-size:11px;color:#2563eb;font-weight:700;font-family:Arial,Helvetica,sans-serif;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['clicks'])); ?></p>
											<p style="margin:2px 0 0;font-size:11px;color:#f59e0b;font-weight:700;font-family:Arial,Helvetica,sans-serif;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['sessions'])); ?></p>
										</td>
									<?php endforeach; ?>
								</tr>
							</table>
						</td>
					</tr>
				</table>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:12px;margin-top:14px;font-family:Arial,Helvetica,sans-serif;">
					<tr style="background:#f6f7f7;">
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php echo esc_html($chart_col_label); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('כניסות', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('משתמשים', 'icomm-metrix'); ?></th>
					</tr>
					<?php foreach ($series as $w) : ?>
						<tr>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;<?php echo $chart_by_week ? ' direction:ltr;' : ''; ?>"><?php echo esc_html((string) $w['label']); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['clicks'])); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['impressions'])); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['sessions'])); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $w['users'])); ?></td>
						</tr>
					<?php endforeach; ?>
				</table>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php endif; ?>

			<!-- Traffic sources -->
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('מקורות התנועה באתר', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($range_label); ?></p>
				<?php if ($channels !== []) : ?>
					<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:13px;">
						<tr style="background:#f6f7f7;">
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מקור תנועה', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('פעילויות', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('משתמשים', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;">%</th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('נטישה', 'icomm-metrix'); ?></th>
						</tr>
						<?php foreach ($channels as $c) :
							$pct = $chan_sessions > 0 ? round(((int) $c['sessions'] / $chan_sessions) * 100, 1) : 0;
							?>
							<tr>
								<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php echo esc_html((string) ($c['dim_label'] !== '' ? $c['dim_label'] : $c['dim_key'])); ?></td>
								<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $c['sessions'])); ?></td>
								<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $c['users'])); ?></td>
								<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n($pct, 1)); ?>%</td>
								<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((float) $c['bounce_rate'], 2)); ?>%</td>
							</tr>
						<?php endforeach; ?>
						<tr style="font-weight:700;background:#f6f7f7;">
							<td style="padding:8px 6px;"><?php esc_html_e('סיכום', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;" dir="ltr"><?php echo esc_html(number_format_i18n($chan_sessions)); ?></td>
							<td style="padding:8px 6px;" dir="ltr"><?php echo esc_html(number_format_i18n($chan_users)); ?></td>
							<td style="padding:8px 6px;" dir="ltr">100%</td>
							<td style="padding:8px 6px;" dir="ltr"><?php echo esc_html(number_format_i18n($chan_bounce_avg, 2)); ?>%</td>
						</tr>
					</table>
				<?php else : ?>
					<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:13px;">
						<tr style="background:#f6f7f7;">
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('ערוץ', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מדד', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('ערך', 'icomm-metrix'); ?></th>
						</tr>
						<tr>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('תנועה לאתר (Analytics)', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('כניסות / משתמשים', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $summary['sessions']) . ' / ' . number_format_i18n((int) $summary['users'])); ?></td>
						</tr>
						<tr>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('חיפוש אורגני (Google)', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('קליקים / חשיפות', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $summary['clicks']) . ' / ' . number_format_i18n((int) $summary['impressions'])); ?></td>
						</tr>
						<tr>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('חיפוש אורגני (Google)', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php esc_html_e('מיקום ממוצע / CTR', 'icomm-metrix'); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((float) $summary['avg_position'], 1) . ' / ' . number_format_i18n($ctr, 2) . '%'); ?></td>
						</tr>
					</table>
				<?php endif; ?>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

			<?php if ($devices !== []) : ?>
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('התפלגות לפי מכשירים', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html($range_label); ?></p>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:13px;">
					<tr style="background:#f6f7f7;">
						<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מכשיר', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('פעילויות', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;">%</th>
						<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('משתמשים', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:8px 6px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('נטישה', 'icomm-metrix'); ?></th>
					</tr>
					<?php foreach (array_slice($devices, 0, 15) as $d) :
						$pct = $dev_sessions > 0 ? round(((int) $d['sessions'] / $dev_sessions) * 100, 2) : 0;
						?>
						<tr>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;"><?php echo esc_html((string) ($d['dim_label'] !== '' ? $d['dim_label'] : $d['dim_key'])); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $d['sessions'])); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n($pct, 2)); ?>%</td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $d['users'])); ?></td>
							<td style="padding:8px 6px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((float) $d['bounce_rate'], 2)); ?>%</td>
						</tr>
					<?php endforeach; ?>
				</table>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php endif; ?>

			<!-- Top queries -->
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('מילות חיפוש מובילות', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('השאילתות שהביאו הכי הרבה קליקים מגוגל', 'icomm-metrix'); ?></p>
				<?php if ($top_queries === []) : ?>
					<p style="margin:0;color:#646970;"><?php esc_html_e('אין נתוני שאילתות לתקופה זו.', 'icomm-metrix'); ?></p>
				<?php else : ?>
					<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:12px;">
						<tr style="background:#f6f7f7;">
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;">#</th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מילת חיפוש', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;">CTR</th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מיקום', 'icomm-metrix'); ?></th>
						</tr>
						<?php foreach ($top_queries as $i => $q) : ?>
							<tr>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html((string) ($i + 1)); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;font-weight:600;"><?php echo esc_html((string) $q['query']); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $q['clicks'])); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $q['impressions'])); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n(((float) $q['ctr']) * 100, 2)); ?>%</td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((float) $q['position'], 1)); ?></td>
							</tr>
						<?php endforeach; ?>
					</table>
				<?php endif; ?>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

			<!-- Top pages -->
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('עמודים מובילים', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('העמודים שקיבלו הכי הרבה קליקים מחיפוש אורגני', 'icomm-metrix'); ?></p>
				<?php if ($top_pages === []) : ?>
					<p style="margin:0;color:#646970;"><?php esc_html_e('אין נתוני עמודים לתקופה זו.', 'icomm-metrix'); ?></p>
				<?php else : ?>
					<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:12px;">
						<tr style="background:#f6f7f7;">
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('עמוד', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;">CTR</th>
							<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מיקום', 'icomm-metrix'); ?></th>
						</tr>
						<?php foreach ($top_pages as $p) :
							$path = (string) wp_parse_url((string) $p['page_url'], PHP_URL_PATH);
							if ($path === '' || $path === false) {
								$path = (string) $p['page_url'];
							}
							?>
							<tr>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;word-break:break-all;" dir="ltr"><?php echo esc_html($path); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $p['clicks'])); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((int) $p['impressions'])); ?></td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n(((float) $p['ctr']) * 100, 2)); ?>%</td>
								<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html(number_format_i18n((float) $p['position'], 1)); ?></td>
							</tr>
						<?php endforeach; ?>
					</table>
				<?php endif; ?>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>

			<?php if ($watch !== []) : ?>
			<?php echo $section_open; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
				<h2 style="margin:0 0 6px;font-size:18px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('מילות מפתח במעקב', 'icomm-metrix'); ?></h2>
				<p style="margin:0 0 14px;color:#646970;font-size:13px;font-family:Arial,Helvetica,sans-serif;"><?php esc_html_e('ביצועי המילים שנבחרו למעקב', 'icomm-metrix'); ?></p>
				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;font-size:12px;">
					<tr style="background:#f6f7f7;">
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מילת מפתח', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
						<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מיקום', 'icomm-metrix'); ?></th>
					</tr>
					<?php foreach ($watch as $wkw) :
						$row = $kw_detail[$wkw] ?? null;
						$winfo = $kw_weekly['rows'][$wkw] ?? null;
						$pos = $row ? (float) $row['position'] : (float) ($winfo['avg'] ?? 0);
						$clicks = $row ? (int) $row['clicks'] : 0;
						$impr = $row ? (int) $row['impressions'] : (int) ($winfo['impressions'] ?? 0);
						?>
						<tr>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;font-weight:600;"><?php echo esc_html($wkw); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html($clicks > 0 ? number_format_i18n($clicks) : '-'); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html($impr > 0 ? number_format_i18n($impr) : '-'); ?></td>
							<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html($pos > 0 ? number_format_i18n($pos, 1) : '-'); ?></td>
						</tr>
					<?php endforeach; ?>
				</table>

				<?php if ($kw_has_weekly_data && $weeks !== []) : ?>
					<p style="margin:16px 0 10px;font-size:14px;font-weight:600;"><?php esc_html_e('מיקומים שבועיים', 'icomm-metrix'); ?></p>
					<div style="overflow-x:auto;">
						<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;font-size:12px;min-width:480px;">
							<tr style="background:#f6f7f7;">
								<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('מילה', 'icomm-metrix'); ?></th>
								<?php foreach ($weeks as $w) : ?>
									<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;" dir="ltr"><?php echo esc_html((string) ($w['label'] ?? '')); ?></th>
								<?php endforeach; ?>
								<th align="right" style="padding:7px 5px;border-bottom:1px solid #dcdcde;"><?php esc_html_e('שינוי', 'icomm-metrix'); ?></th>
							</tr>
							<?php foreach ($kw_weekly['rows'] as $kw => $info) :
								$sp = $info['start_pos'];
								$ep = $info['end_pos'];
								$delta = ($sp !== null && $ep !== null) ? round((float) $sp - (float) $ep, 1) : null;
								?>
								<tr>
									<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;font-weight:600;"><?php echo esc_html($kw); ?></td>
									<?php foreach ($weeks as $w) :
										$ws = (string) ($w['start'] ?? '');
										$v = $info['weeks'][$ws] ?? null;
										?>
										<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;" dir="ltr"><?php echo esc_html($v !== null ? number_format_i18n((float) $v, 1) : '-'); ?></td>
									<?php endforeach; ?>
									<td style="padding:7px 5px;border-bottom:1px solid #f0f0f1;font-weight:700;color:<?php echo ($delta !== null && $delta > 0) ? '#00a32a' : (($delta !== null && $delta < 0) ? '#d63638' : '#1d2327'); ?>;" dir="ltr">
										<?php
										if ($delta === null) {
											echo '-';
										} else {
											echo esc_html(($delta > 0 ? '▲ ' : ($delta < 0 ? '▼ ' : '')) . number_format_i18n(abs($delta), 1));
										}
										?>
									</td>
								</tr>
							<?php endforeach; ?>
						</table>
					</div>
				<?php endif; ?>
			<?php echo $section_close; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php endif; ?>

			<p style="margin:12px 0 0;font-size:12px;color:#8c8f94;font-family:Arial,Helvetica,sans-serif;"><?php echo esc_html(sprintf(__('הופק מ-%s · icomm metrix', 'icomm-metrix'), $agency)); ?></p>
		</td></tr>
		</table>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * @param array<string, string>|null $period When null, uses previous calendar month (auto cron).
	 * @return array{ok:bool,error?:string,detail?:string}
	 */
	public static function send_monthly_email(string $to = '', ?array $period = null): array {
		if (!IComm_SM_Features::can_use('client_email')) {
			return ['ok' => false, 'error' => 'feature_locked'];
		}
		$s = IComm_SM_Settings::get();
		if ($to === '') {
			$to = sanitize_email((string) ($s['client_report_email'] ?? ''));
		} else {
			$to = sanitize_email($to);
		}
		if ($to === '' || !is_email($to)) {
			return ['ok' => false, 'error' => 'invalid_email'];
		}

		$period = is_array($period) ? $period : self::previous_month_period();
		$site = (string) (($period['domain'] ?? '') !== '' ? $period['domain'] : wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES));
		$subject = sprintf(
			'[icomm metrix] %s - %s',
			$site,
			sprintf(__('דוח חודשי %s', 'icomm-metrix'), (string) $period['label'])
		);

		// HTML in the email body (same markup as the admin preview). Dompdf PDF breaks Hebrew RTL.
		$html = self::monthly_client_report_html($period);
		$body = '<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
			. '<style type="text/css">body,table,td,th,p,span,strong,h1,h2{font-family:Arial,Helvetica,sans-serif !important;}</style>'
			. '</head><body dir="rtl" style="direction:rtl;text-align:right;margin:0;padding:20px;background:#f0f0f1;font-family:Arial,Helvetica,sans-serif;color:#1d2327;">'
			. $html
			. '</body></html>';

		$from_email = sanitize_email((string) get_option('admin_email'));
		$from_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$headers = ['Content-Type: text/html; charset=UTF-8'];
		if ($from_email !== '' && is_email($from_email)) {
			$headers[] = 'From: ' . self::format_from_header($from_name, $from_email);
			$headers[] = 'Reply-To: ' . $from_email;
		}

		$mail_error = '';
		$fail_cb = static function ($err) use (&$mail_error): void {
			if (is_wp_error($err)) {
				$mail_error = $err->get_error_message();
			}
		};
		add_action('wp_mail_failed', $fail_cb, 10, 1);
		$ok = (bool) wp_mail($to, $subject, $body, $headers);
		remove_action('wp_mail_failed', $fail_cb, 10);

		if (!$ok && $mail_error === '' && class_exists('icomm_Smtp_Core', false) && method_exists('icomm_Smtp_Core', 'get_last_graph_send_error')) {
			$g = (string) icomm_Smtp_Core::get_last_graph_send_error();
			if ($g !== '') {
				$mail_error = $g;
			}
		}

		update_option(
			'icomm_sm_last_client_mail',
			[
				'at' => current_time('timestamp'),
				'to' => $to,
				'ok' => $ok ? 1 : 0,
				'period' => (string) $period['label'],
				'pdf' => 0,
				'format' => 'html',
				'error' => $ok ? '' : ($mail_error !== '' ? $mail_error : 'send_failed'),
			],
			false
		);

		if ($ok) {
			return ['ok' => true];
		}
		$out = ['ok' => false, 'error' => 'send_failed'];
		if ($mail_error !== '') {
			$out['detail'] = $mail_error;
		}
		return $out;
	}

	/**
	 * Styled RTL HTML email for monthly SEO trend chart.
	 *
	 * @param bool $include_analysis Include YoY / long-term / recommendations.
	 */
	public static function trend_email_html(bool $include_analysis = true): string {
		if (!IComm_SM_Features::can_use('seo_trend')) {
			return '';
		}
		$trend = IComm_SM_Recommendations::seo_monthly_trend();
		$months = is_array($trend['months'] ?? null) ? $trend['months'] : [];
		$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$s = IComm_SM_Settings::get();
		$agency = '';
		$logo = '';
		if (IComm_SM_Features::can_use('report_branding')) {
			$agency = trim((string) ($s['agency_name'] ?? ''));
			$logo = esc_url((string) ($s['agency_logo_url'] ?? ''));
		}

		$dir = (string) ($trend['direction'] ?? 'unknown');
		$dir_label = (string) ($trend['direction_label'] ?? '');
		$dir_bg = '#f0f0f1';
		$dir_fg = '#1d2327';
		if ($dir === 'up') {
			$dir_bg = '#edfaef';
			$dir_fg = '#007017';
		} elseif ($dir === 'down') {
			$dir_bg = '#fcf0f1';
			$dir_fg = '#b32d2e';
		} elseif ($dir === 'stable') {
			$dir_bg = '#fcf9e8';
			$dir_fg = '#996800';
		}

		$deltas = is_array($trend['deltas'] ?? null) ? $trend['deltas'] : [];
		$yoy = is_array($trend['yoy'] ?? null) ? $trend['yoy'] : [];
		$long = is_array($trend['long_term'] ?? null) ? $trend['long_term'] : [];
		$recs = is_array($trend['recommendations'] ?? null) ? $trend['recommendations'] : [];

		$max_c = 1;
		$max_i = 1;
		foreach ($months as $m) {
			$max_c = max($max_c, (int) ($m['clicks'] ?? 0));
			$max_i = max($max_i, (int) ($m['impressions'] ?? 0));
		}

		// Newest first for compact table rows (print / A4 friendly).
		$months_newest_first = array_reverse($months);
		// Chart: last 6 months, oldest→newest. With dir=rtl, first cell is on the RIGHT (matches screen).
		$chart_months = array_slice($months, -6);
		$max_c_chart = 1;
		$max_i_chart = 1;
		foreach ($chart_months as $m) {
			$max_c_chart = max($max_c_chart, (int) ($m['clicks'] ?? 0));
			$max_i_chart = max($max_i_chart, (int) ($m['impressions'] ?? 0));
		}
		$chart_h = 120; // px, same visual weight as dashboard bars

		ob_start();
		?>
		<style type="text/css">
			.icomm-sm-trend-mail, .icomm-sm-trend-mail td, .icomm-sm-trend-mail th,
			.icomm-sm-trend-mail p, .icomm-sm-trend-mail span, .icomm-sm-trend-mail strong,
			.icomm-sm-trend-mail h1, .icomm-sm-trend-mail h2 {
				font-family: Arial, Helvetica, sans-serif !important;
			}
			.icomm-sm-trend-mail, .icomm-sm-trend-mail td, .icomm-sm-trend-mail th,
			.icomm-sm-trend-mail p, .icomm-sm-trend-mail span, .icomm-sm-trend-mail strong {
				font-size: 12pt !important;
			}
			.icomm-sm-trend-mail h1 { font-size: 16pt !important; }
			.icomm-sm-trend-mail h2 { font-size: 14pt !important; }
		</style>
		<!--[if mso]>
		<style type="text/css">
			.icomm-sm-trend-mail, .icomm-sm-trend-mail td, .icomm-sm-trend-mail th,
			.icomm-sm-trend-mail p, .icomm-sm-trend-mail span, .icomm-sm-trend-mail strong {
				font-family: Arial, Helvetica, sans-serif !important;
				font-size: 12pt !important;
			}
			.icomm-sm-trend-mail h1 { font-size: 16pt !important; }
			.icomm-sm-trend-mail h2 { font-size: 14pt !important; }
		</style>
		<![endif]-->
		<table role="presentation" class="icomm-sm-trend-mail" cellpadding="0" cellspacing="0" border="0" width="700" dir="rtl" lang="he" style="width:700px;max-width:700px;margin:0 auto;direction:rtl;text-align:right;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;color:#1d2327;background:#ffffff;">
			<tr>
				<td style="font-family:Arial,Helvetica,sans-serif;padding:16px 14px;font-size:16px;font-size:12pt;line-height:1.5;">
			<?php if ($logo !== '') : ?>
				<p style="margin:0 0 8px;"><img src="<?php echo esc_url($logo); ?>" alt="" style="max-height:40px;width:auto;border:0;" /></p>
			<?php endif; ?>
			<h1 style="font-family:Arial,Helvetica,sans-serif;margin:0 0 4px;font-size:16pt;line-height:1.3;"><?php echo esc_html(sprintf(__('מגמת SEO - %s', 'icomm-metrix'), $site)); ?></h1>
			<?php if ($agency !== '') : ?>
				<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 4px;color:#50575e;font-size:16px;font-size:12pt;"><?php echo esc_html($agency); ?></p>
			<?php endif; ?>
			<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 10px;color:#646970;font-size:16px;font-size:12pt;"><?php echo esc_html(sprintf(__('עודכן: %s', 'icomm-metrix'), wp_date('d/m/Y H:i'))); ?></p>

			<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 10px;">
				<tr>
					<td style="font-family:Arial,Helvetica,sans-serif;background:<?php echo esc_attr($dir_bg); ?>;color:<?php echo esc_attr($dir_fg); ?>;padding:4px 10px;font-weight:700;font-size:16px;font-size:12pt;">
						<?php echo esc_html($dir_label); ?>
					</td>
				</tr>
			</table>

			<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 12px;font-size:16px;font-size:12pt;line-height:1.45;"><?php echo esc_html((string) ($trend['summary'] ?? '')); ?></p>

			<h2 style="font-family:Arial,Helvetica,sans-serif;margin:0 0 12px;font-size:14pt;border-bottom:2px solid #1d4ed8;padding-bottom:6px;"><?php esc_html_e('השוואת חודשים', 'icomm-metrix'); ?></h2>

			<?php if ($months_newest_first === []) : ?>
				<p style="font-family:Arial,Helvetica,sans-serif;color:#646970;margin:0 0 16px;font-size:16px;font-size:12pt;"><?php esc_html_e('אין נתונים חודשיים להצגה.', 'icomm-metrix'); ?></p>
			<?php else : ?>
				<?php if ($chart_months !== []) : ?>
					<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 10px;font-size:16px;font-size:12pt;color:#50575e;line-height:1.5;">
						<strong style="color:#1d2327;"><?php esc_html_e('תצוגה מהירה', 'icomm-metrix'); ?></strong>
						<span style="color:#8c8f94;">
							<?php
							echo esc_html(
								count($months) > 6
									? __(' · 6 חודשים אחרונים (ישן מימין ← חדש משמאל)', 'icomm-metrix')
									: __(' · ישן מימין ← חדש משמאל', 'icomm-metrix')
							);
							?>
						</span>
					</p>
					<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 8px;font-size:16px;font-size:12pt;color:#50575e;">
						<span style="display:inline-block;width:12px;height:12px;background:#1d4ed8;border-radius:2px;margin-left:6px;vertical-align:middle;"></span><?php esc_html_e('קליקים', 'icomm-metrix'); ?>
						&nbsp;&nbsp;
						<span style="display:inline-block;width:12px;height:12px;background:#ea580c;border-radius:2px;margin-left:6px;vertical-align:middle;"></span><?php esc_html_e('חשיפות', 'icomm-metrix'); ?>
					</p>
					<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="margin:0 0 8px;border-collapse:collapse;background:#fafafa;border:1px solid #dcdcde;">
						<tr>
							<td style="padding:14px 8px 10px;" align="center">
								<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" dir="rtl" style="margin:0 auto;border-collapse:collapse;direction:rtl;">
									<tr>
										<?php foreach ($chart_months as $m) : ?>
											<?php
											$c = (int) ($m['clicks'] ?? 0);
											$i = (int) ($m['impressions'] ?? 0);
											$hc = (int) max(4, round(($c / $max_c_chart) * $chart_h));
											$hi = (int) max(4, round(($i / $max_i_chart) * $chart_h));
											if ($c === 0 && $i === 0) {
												$hc = 3;
												$hi = 3;
											}
											$pad_c = max(0, $chart_h - $hc);
											$pad_i = max(0, $chart_h - $hi);
											?>
											<td valign="bottom" align="center" width="100" style="padding:0 5px 8px;width:100px;">
												<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin:0 auto 8px;border-collapse:collapse;">
													<tr>
														<td valign="bottom" style="padding:0 3px;border-bottom:1px solid #dcdcde;">
															<?php echo self::email_vbar_html('#1d4ed8', $hc, $pad_c, 16); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
														</td>
														<td valign="bottom" style="padding:0 3px;border-bottom:1px solid #dcdcde;">
															<?php echo self::email_vbar_html('#ea580c', $hi, $pad_i, 16); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
														</td>
													</tr>
												</table>
												<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 4px;font-size:12pt;line-height:1.3;color:#1d2327;font-weight:700;"><?php echo esc_html((string) ($m['label'] ?? '')); ?></p>
												<p style="font-family:Arial,Helvetica,sans-serif;margin:0;font-size:12pt;line-height:1.35;color:#1d4ed8;font-weight:700;"><?php echo esc_html((string) $c); ?></p>
												<p style="font-family:Arial,Helvetica,sans-serif;margin:2px 0 0;font-size:12pt;line-height:1.35;color:#ea580c;font-weight:700;"><?php echo esc_html((string) $i); ?></p>
											</td>
										<?php endforeach; ?>
									</tr>
								</table>
							</td>
						</tr>
					</table>
				<?php endif; ?>

				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;margin:18px 0 6px;border-collapse:collapse;">
					<tr>
						<td style="padding:0;border-top:1px solid #dcdcde;font-size:0;line-height:0;height:1px;">&nbsp;</td>
					</tr>
				</table>
				<p style="font-family:Arial,Helvetica,sans-serif;margin:14px 0 10px;font-size:16px;font-size:12pt;color:#1d2327;font-weight:700;"><?php esc_html_e('טבלת נתונים לפי חודש', 'icomm-metrix'); ?></p>

				<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="680" style="width:680px;max-width:680px;margin:0 0 18px;border-collapse:collapse;table-layout:fixed;font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;">
					<tr style="background:#f6f7f7;">
						<th align="right" width="160" style="font-family:Arial,Helvetica,sans-serif;width:160px;padding:10px 12px;border:1px solid #dcdcde;font-size:16px;font-size:12pt;"><?php esc_html_e('חודש', 'icomm-metrix'); ?></th>
						<th align="center" width="140" style="font-family:Arial,Helvetica,sans-serif;width:140px;padding:10px 12px;border:1px solid #dcdcde;font-size:16px;font-size:12pt;"><?php esc_html_e('קליקים', 'icomm-metrix'); ?></th>
						<th align="center" width="140" style="font-family:Arial,Helvetica,sans-serif;width:140px;padding:10px 12px;border:1px solid #dcdcde;font-size:16px;font-size:12pt;"><?php esc_html_e('חשיפות', 'icomm-metrix'); ?></th>
						<th align="center" width="110" style="font-family:Arial,Helvetica,sans-serif;width:110px;padding:10px 12px;border:1px solid #dcdcde;font-size:16px;font-size:12pt;"><?php esc_html_e('CTR', 'icomm-metrix'); ?></th>
						<th align="center" width="130" style="font-family:Arial,Helvetica,sans-serif;width:130px;padding:10px 12px;border:1px solid #dcdcde;font-size:16px;font-size:12pt;"><?php esc_html_e('מיקום', 'icomm-metrix'); ?></th>
					</tr>
					<?php
					$row_i = 0;
					foreach ($months_newest_first as $m) :
						$row_i++;
						$c = (int) ($m['clicks'] ?? 0);
						$i = (int) ($m['impressions'] ?? 0);
						$bar_c = (int) max(0, min(100, round(($c / $max_c) * 100)));
						$bar_i = (int) max(0, min(100, round(($i / $max_i) * 100)));
						$row_bg = ($row_i % 2 === 0) ? 'background:#fafafa;' : 'background:#ffffff;';
						?>
						<tr style="<?php echo esc_attr($row_bg); ?>">
							<td align="right" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;padding:9px 12px;border:1px solid #dcdcde;white-space:nowrap;line-height:1.4;<?php echo esc_attr($row_bg); ?>"><?php echo esc_html((string) ($m['label'] ?? '')); ?><?php echo !empty($m['is_partial']) ? ' *' : ''; ?></td>
							<td align="center" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;padding:9px 12px;border:1px solid #dcdcde;line-height:1.4;<?php echo esc_attr($row_bg); ?>">
								<span style="font-weight:700;"><?php echo esc_html((string) $c); ?></span>
								<?php if ($bar_c > 0) : ?>
									<?php echo self::email_hbar_html('#1d4ed8', $bar_c, 88); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php endif; ?>
							</td>
							<td align="center" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;padding:9px 12px;border:1px solid #dcdcde;line-height:1.4;<?php echo esc_attr($row_bg); ?>">
								<span style="font-weight:700;"><?php echo esc_html((string) $i); ?></span>
								<?php if ($bar_i > 0) : ?>
									<?php echo self::email_hbar_html('#ea580c', $bar_i, 88); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php endif; ?>
							</td>
							<td align="center" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;padding:9px 12px;border:1px solid #dcdcde;line-height:1.4;<?php echo esc_attr($row_bg); ?>"><?php echo esc_html((string) round(((float) ($m['ctr'] ?? 0)) * 100, 1)); ?>%</td>
							<td align="center" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;padding:9px 12px;border:1px solid #dcdcde;line-height:1.4;<?php echo esc_attr($row_bg); ?>"><?php echo esc_html((string) (float) ($m['position'] ?? 0)); ?></td>
						</tr>
					<?php endforeach; ?>
				</table>
			<?php endif; ?>

			<h2 style="font-family:Arial,Helvetica,sans-serif;margin:8px 0 12px;font-size:14pt;border-bottom:2px solid #ea580c;padding-bottom:6px;"><?php esc_html_e('חודש מול חודש קודם', 'icomm-metrix'); ?></h2>
			<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="680" style="font-family:Arial,Helvetica,sans-serif;width:680px;max-width:680px;margin:0 0 16px;border-collapse:collapse;table-layout:fixed;font-size:16px;font-size:12pt;">
				<?php
				$cells = [
					[__('קליקים', 'icomm-metrix'), (float) ($deltas['clicks_pct'] ?? 0), '%'],
					[__('חשיפות', 'icomm-metrix'), (float) ($deltas['impressions_pct'] ?? 0), '%'],
					[__('CTR', 'icomm-metrix'), (float) ($deltas['ctr_pct'] ?? 0), '%'],
					[__('שיפור מיקום', 'icomm-metrix'), (float) ($deltas['position_delta'] ?? 0), ''],
				];
				for ($row_i = 0; $row_i < 4; $row_i += 2) :
					?>
					<tr>
						<?php for ($col = 0; $col < 2; $col++) :
							$cell = $cells[ $row_i + $col ];
							$val = (float) $cell[1];
							$color = $val >= 0 ? '#007017' : '#b32d2e';
							$txt = ($val > 0 ? '+' : '') . (string) $val . $cell[2];
							?>
							<td width="50%" style="width:50%;padding:5px;vertical-align:top;">
								<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;width:100%;border-collapse:collapse;background:#f6f7f7;border:1px solid #dcdcde;">
									<tr>
										<td align="right" style="font-family:Arial,Helvetica,sans-serif;padding:10px 12px;font-size:16px;font-size:12pt;color:#50575e;"><?php echo esc_html((string) $cell[0]); ?></td>
										<td align="left" dir="ltr" style="font-family:Arial,Helvetica,sans-serif;padding:10px 12px;font-size:16px;font-size:12pt;font-weight:700;color:<?php echo esc_attr($color); ?>;white-space:nowrap;"><?php echo esc_html($txt); ?></td>
									</tr>
								</table>
							</td>
						<?php endfor; ?>
					</tr>
				<?php endfor; ?>
			</table>

			<?php if ($include_analysis) : ?>
				<?php if (!empty($yoy['available']) || !empty($long['available'])) : ?>
					<h2 style="font-family:Arial,Helvetica,sans-serif;margin:0 0 6px;font-size:14pt;"><?php esc_html_e('ניתוח נוסף', 'icomm-metrix'); ?></h2>
					<?php if (!empty($yoy['available'])) : ?>
						<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="680" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;width:680px;margin:0 0 10px;border-collapse:collapse;background:#f8fafc;border:1px solid #dcdcde;">
							<tr>
								<td style="padding:8px 10px;">
									<strong style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;"><?php esc_html_e('שנה מול שנה', 'icomm-metrix'); ?></strong>
									<p style="font-family:Arial,Helvetica,sans-serif;margin:4px 0;font-size:16px;font-size:12pt;color:#50575e;"><?php echo esc_html((string) ($yoy['label'] ?? '')); ?></p>
									<p style="font-family:Arial,Helvetica,sans-serif;margin:0;font-size:16px;font-size:12pt;">
										<?php esc_html_e('קליקים', 'icomm-metrix'); ?>:
										<strong style="color:<?php echo ((float) ($yoy['clicks_pct'] ?? 0) >= 0) ? '#007017' : '#b32d2e'; ?>;">
											<?php echo esc_html((((float) ($yoy['clicks_pct'] ?? 0) > 0) ? '+' : '') . (string) ($yoy['clicks_pct'] ?? 0)); ?>%
										</strong>
										·
										<?php esc_html_e('חשיפות', 'icomm-metrix'); ?>:
										<strong style="color:<?php echo ((float) ($yoy['impressions_pct'] ?? 0) >= 0) ? '#007017' : '#b32d2e'; ?>;">
											<?php echo esc_html((((float) ($yoy['impressions_pct'] ?? 0) > 0) ? '+' : '') . (string) ($yoy['impressions_pct'] ?? 0)); ?>%
										</strong>
									</p>
								</td>
							</tr>
						</table>
					<?php endif; ?>
					<?php if (!empty($long['available'])) : ?>
						<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="680" style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;width:680px;margin:0 0 12px;border-collapse:collapse;background:#f8fafc;border:1px solid #dcdcde;">
							<tr>
								<td style="padding:8px 10px;">
									<strong style="font-family:Arial,Helvetica,sans-serif;font-size:16px;font-size:12pt;"><?php esc_html_e('מגמה ארוכה (3 מול 3)', 'icomm-metrix'); ?></strong>
									<p style="font-family:Arial,Helvetica,sans-serif;margin:4px 0;font-size:16px;font-size:12pt;color:#50575e;"><?php echo esc_html((string) ($long['label'] ?? '')); ?></p>
									<p style="font-family:Arial,Helvetica,sans-serif;margin:0;font-size:16px;font-size:12pt;">
										<?php esc_html_e('קליקים', 'icomm-metrix'); ?>:
										<strong style="color:<?php echo ((float) ($long['clicks_pct'] ?? 0) >= 0) ? '#007017' : '#b32d2e'; ?>;">
											<?php echo esc_html((((float) ($long['clicks_pct'] ?? 0) > 0) ? '+' : '') . (string) ($long['clicks_pct'] ?? 0)); ?>%
										</strong>
										·
										<?php esc_html_e('חשיפות', 'icomm-metrix'); ?>:
										<strong style="color:<?php echo ((float) ($long['impressions_pct'] ?? 0) >= 0) ? '#007017' : '#b32d2e'; ?>;">
											<?php echo esc_html((((float) ($long['impressions_pct'] ?? 0) > 0) ? '+' : '') . (string) ($long['impressions_pct'] ?? 0)); ?>%
										</strong>
									</p>
								</td>
							</tr>
						</table>
					<?php endif; ?>
				<?php endif; ?>

				<?php if ($recs !== []) : ?>
					<h2 style="font-family:Arial,Helvetica,sans-serif;margin:0 0 10px;font-size:14pt;"><?php esc_html_e('איך לפעול הלאה', 'icomm-metrix'); ?></h2>
					<?php foreach ($recs as $r) : ?>
						<?php
						$prio = (string) ($r['priority'] ?? 'low');
						$border = '#00a32a';
						if ($prio === 'high') {
							$border = '#d63638';
						} elseif ($prio === 'medium') {
							$border = '#dba617';
						}
						?>
						<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="680" dir="rtl" style="font-family:Arial,Helvetica,sans-serif;font-size:12pt;width:680px;margin:0 0 8px;border-collapse:collapse;border:1px solid #dcdcde;direction:rtl;">
							<tr>
								<td width="4" bgcolor="<?php echo esc_attr($border); ?>" style="width:4px;background-color:<?php echo esc_attr($border); ?>;font-size:0;line-height:0;">&nbsp;</td>
								<td style="padding:12px 14px;font-family:Arial,Helvetica,sans-serif;font-size:12pt;">
									<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="100%" style="width:100%;border-collapse:collapse;">
										<tr>
											<td style="font-family:Arial,Helvetica,sans-serif;font-size:12pt;font-weight:700;color:#1d2327;padding:0 0 6px;"><?php echo esc_html((string) ($r['title'] ?? '')); ?></td>
										</tr>
										<tr>
											<td style="font-family:Arial,Helvetica,sans-serif;font-size:12pt;color:#50575e;line-height:1.5;padding:0;"><?php echo esc_html((string) ($r['details'] ?? '')); ?></td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					<?php endforeach; ?>
				<?php endif; ?>
			<?php else : ?>
				<p style="font-family:Arial,Helvetica,sans-serif;margin:0 0 10px;font-size:16px;font-size:12pt;color:#646970;"><?php esc_html_e('המייל נשלח ללא ניתוח והמלצות (גרף ונתונים בלבד).', 'icomm-metrix'); ?></p>
			<?php endif; ?>

			<?php if (!empty($trend['range_note'])) : ?>
				<p style="font-family:Arial,Helvetica,sans-serif;margin:12px 0 0;font-size:16px;font-size:12pt;color:#646970;"><?php echo esc_html((string) $trend['range_note']); ?></p>
			<?php endif; ?>
			<p style="font-family:Arial,Helvetica,sans-serif;margin:8px 0 0;font-size:16px;font-size:12pt;color:#8c8f94;"><?php esc_html_e('נשלח מ-icomm metrix · מותאם להדפסה A4', 'icomm-metrix'); ?></p>
				</td>
			</tr>
		</table>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * @return array{ok:bool,error?:string,detail?:string}
	 */
	public static function send_trend_email(string $to, bool $include_analysis = true): array {
		if (!IComm_SM_Features::can_use('seo_trend')) {
			return ['ok' => false, 'error' => 'feature_locked'];
		}
		$to = sanitize_email($to);
		if ($to === '' || !is_email($to)) {
			return ['ok' => false, 'error' => 'invalid_email'];
		}
		$html = self::trend_email_html($include_analysis);
		if (trim($html) === '') {
			return ['ok' => false, 'error' => 'no_data'];
		}
		$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$subject = sprintf(
			'[icomm metrix] %s - %s',
			$site,
			$include_analysis ? __('מגמת SEO + ניתוח', 'icomm-metrix') : __('מגמת SEO', 'icomm-metrix')
		);
		$body = '<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
			. '<style type="text/css">body,table,td,th,p,span,strong,h1,h2{font-family:Arial,Helvetica,sans-serif !important;}body,table,td,th,p,span,strong{font-size:12pt !important;}h1{font-size:16pt !important;}h2{font-size:14pt !important;}</style>'
			. '</head>'
			. '<body dir="rtl" style="direction:rtl;text-align:right;margin:0;padding:20px;background:#f0f0f1;font-family:Arial,Helvetica,sans-serif;font-size:12pt;line-height:1.5;">'
			. $html
			. '</body></html>';

		$from_email = sanitize_email((string) get_option('admin_email'));
		$from_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$headers = [
			'Content-Type: text/html; charset=UTF-8',
		];
		if ($from_email !== '' && is_email($from_email)) {
			$headers[] = 'From: ' . self::format_from_header($from_name, $from_email);
			$headers[] = 'Reply-To: ' . $from_email;
		}

		$mail_error = '';
		$fail_cb = static function ($err) use (&$mail_error): void {
			if (is_wp_error($err)) {
				$mail_error = $err->get_error_message();
			}
		};
		add_action('wp_mail_failed', $fail_cb, 10, 1);
		$ok = (bool) wp_mail($to, $subject, $body, $headers);
		remove_action('wp_mail_failed', $fail_cb, 10);

		// Graph/SMTP plugins sometimes set a static last error without firing wp_mail_failed cleanly.
		if (!$ok && $mail_error === '' && class_exists('icomm_Smtp_Core', false) && method_exists('icomm_Smtp_Core', 'get_last_graph_send_error')) {
			$g = (string) icomm_Smtp_Core::get_last_graph_send_error();
			if ($g !== '') {
				$mail_error = $g;
			}
		}

		update_option(
			'icomm_sm_last_trend_mail',
			[
				'at' => current_time('timestamp'),
				'to' => $to,
				'ok' => $ok ? 1 : 0,
				'analysis' => $include_analysis ? 1 : 0,
				'error' => $ok ? '' : ($mail_error !== '' ? $mail_error : 'send_failed'),
			],
			false
		);

		if ($ok) {
			return ['ok' => true];
		}
		return [
			'ok' => false,
			'error' => 'send_failed',
			'detail' => $mail_error !== '' ? $mail_error : __('wp_mail החזיר false (בדקו icomm WP SMTP / יומן מיילים).', 'icomm-metrix'),
		];
	}

	/**
	 * Vertical bar for email clients (Outlook strips CSS height on divs).
	 * Spacer row + colored row inside a fixed chart height.
	 */
	private static function email_vbar_html(string $color, int $bar_h, int $pad_h, int $width = 16): string {
		$color = preg_match('/^#[0-9a-fA-F]{3,8}$/', $color) ? $color : '#1d4ed8';
		$bar_h = max(1, min(200, $bar_h));
		$pad_h = max(0, min(200, $pad_h));
		$width = max(8, min(40, $width));
		$html = '<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="' . $width . '" style="width:' . $width . 'px;border-collapse:collapse;">';
		if ($pad_h > 0) {
			$html .= '<tr><td height="' . $pad_h . '" style="height:' . $pad_h . 'px;line-height:' . $pad_h . 'px;font-size:0;mso-line-height-rule:exactly;">&nbsp;</td></tr>';
		}
		$html .= '<tr><td height="' . $bar_h . '" bgcolor="' . esc_attr($color) . '" style="height:' . $bar_h . 'px;line-height:' . $bar_h . 'px;font-size:0;background-color:' . esc_attr($color) . ';mso-line-height-rule:exactly;">&nbsp;</td></tr>';
		$html .= '</table>';
		return $html;
	}

	/**
	 * Horizontal mini-bar for table cells (email-safe).
	 *
	 * @param int $pct 0-100 fill percentage.
	 */
	private static function email_hbar_html(string $color, int $pct, int $total_w = 88): string {
		$color = preg_match('/^#[0-9a-fA-F]{3,8}$/', $color) ? $color : '#1d4ed8';
		$pct = max(0, min(100, $pct));
		$total_w = max(40, min(120, $total_w));
		$fill = (int) max(1, round($total_w * ($pct / 100)));
		$rest = max(0, $total_w - $fill);
		// Height 2px, delicate like the dashboard mini-bars (Outlook respects td height better than div).
		$html = '<table role="presentation" cellpadding="0" cellspacing="0" border="0" width="' . $total_w . '" align="center" style="margin:4px auto 0;width:' . $total_w . 'px;border-collapse:collapse;">';
		$html .= '<tr>';
		$html .= '<td width="' . $fill . '" height="2" bgcolor="' . esc_attr($color) . '" style="width:' . $fill . 'px;height:2px;max-height:2px;font-size:0;line-height:2px;mso-line-height-rule:exactly;background-color:' . esc_attr($color) . ';">&nbsp;</td>';
		if ($rest > 0) {
			$html .= '<td width="' . $rest . '" height="2" bgcolor="#e8e8e8" style="width:' . $rest . 'px;height:2px;max-height:2px;font-size:0;line-height:2px;mso-line-height-rule:exactly;background-color:#e8e8e8;">&nbsp;</td>';
		}
		$html .= '</tr></table>';
		return $html;
	}

	private static function format_from_header(string $name, string $email): string {
		$name = trim(str_replace(["\r", "\n"], '', $name));
		$email = trim($email);
		if ($name === '') {
			return $email;
		}
		// Keep ASCII-safe From display for picky SMTP relays.
		$name = wp_strip_all_tags($name);
		return sprintf('%s <%s>', $name, $email);
	}
}
