<?php

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

final class IComm_SM_Alerts {

	private const OPT_LAST_SIG = 'icomm_sm_alerts_last_sig';
	private const OPT_LAST_SENT_AT = 'icomm_sm_alerts_last_sent_at';

	public static function init(): void {
		// reserved for future hooks
	}

	public static function after_successful_sync(): void {
		if (!is_admin()) {
			return;
		}
		if (!IComm_SM_Features::can_use('alerts')) {
			return;
		}
		$s = IComm_SM_Settings::get();
		if (empty($s['alerts_enabled'])) {
			return;
		}

		$period_days = max(3, min(30, (int) ($s['alerts_period_days'] ?? 7)));
		$drop_pct = max(5, min(95, (int) ($s['alerts_drop_pct'] ?? 30)));
		$min_clicks = max(0, (int) ($s['alerts_min_clicks'] ?? 20));

		$cur = IComm_SM_DB::summary_window($period_days, 0);
		$prev = IComm_SM_DB::summary_window($period_days, $period_days);

		$signals = self::detect_drops($prev, $cur, $drop_pct, $min_clicks);
		$index_alerts = self::maybe_check_indexing($s);
		$signals = array_merge($signals, $index_alerts);

		if ($signals === []) {
			return;
		}

		$to = self::recipients($s);
		if ($to === []) {
			return;
		}

		$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$subject = sprintf('[icomm metrix] %s, התראה', $site);

		$body = self::email_html($signals, $period_days, $prev, $cur);
		$sig = md5($subject . '|' . $body);

		$last_sig = (string) get_option(self::OPT_LAST_SIG, '');
		$last_sent = (int) get_option(self::OPT_LAST_SENT_AT, 0);
		$now = current_time('timestamp');
		if ($last_sig === $sig && $last_sent > 0 && ($now - $last_sent) < (20 * HOUR_IN_SECONDS)) {
			return;
		}

		$headers = ['Content-Type: text/html; charset=UTF-8'];
		$ok = true;
		foreach ($to as $addr) {
			$ok = (bool) wp_mail($addr, $subject, $body, $headers) && $ok;
		}
		if ($ok) {
			update_option(self::OPT_LAST_SIG, $sig, false);
			update_option(self::OPT_LAST_SENT_AT, $now, false);
		}
	}

	/**
	 * @param array{clicks:int,impressions:int,sessions:int,users:int,period_days:int} $prev
	 * @param array{clicks:int,impressions:int,sessions:int,users:int,period_days:int} $cur
	 * @return array<int, array{title:string, severity:string, details:string}>
	 */
	private static function detect_drops(array $prev, array $cur, int $drop_pct, int $min_clicks): array {
		$items = [];

		$metrics = [
			'clicks' => __('קליקים מגוגל', 'icomm-metrix'),
			'impressions' => __('חשיפות בגוגל', 'icomm-metrix'),
			'sessions' => __('כניסות לאתר', 'icomm-metrix'),
		];

		foreach ($metrics as $k => $label) {
			$pv = (int) ($prev[$k] ?? 0);
			$cv = (int) ($cur[$k] ?? 0);
			if ($k === 'clicks' && $pv < $min_clicks) {
				continue;
			}
			if ($pv <= 0) {
				continue;
			}
			$delta = $cv - $pv;
			$pct = (int) round(($delta / $pv) * 100);
			if ($pct > -$drop_pct) {
				continue;
			}

			$sev = $pct <= -60 ? 'critical' : ($pct <= -40 ? 'high' : 'medium');
			$items[] = [
				'title' => sprintf(__('%s ירדו ב-%d%%', 'icomm-metrix'), $label, abs($pct)),
				'severity' => $sev,
				'details' => sprintf(__('%1$s: %2$d → %3$d', 'icomm-metrix'), $label, $pv, $cv),
			];
		}

		return $items;
	}

	/**
	 * @param array<string,mixed> $s
	 * @return array<int, array{title:string, severity:string, details:string}>
	 */
	private static function maybe_check_indexing(array $s): array {
		if (!IComm_SM_Features::can_use('gsc_indexing')) {
			return [];
		}
		if (empty($s['index_watch_enabled'])) {
			return [];
		}
		if (!IComm_SM_Settings::is_gsc_ready()) {
			return [];
		}
		$urls = $s['index_watch_urls'] ?? [];
		if (!is_array($urls)) {
			$urls = [];
		}
		$urls = array_values(array_unique(array_filter(array_map('trim', array_map('strval', $urls)))));
		if ($urls === []) {
			return [];
		}
		$max = max(1, min(30, (int) ($s['index_watch_max'] ?? 5)));
		$urls = array_slice($urls, 0, $max);

		$res = IComm_SM_Remote::inspect_urls($urls, $max);
		if (empty($res['ok']) || empty($res['results']) || !is_array($res['results'])) {
			return [[
				'title' => __('בדיקת אינדוקס נכשלה', 'icomm-metrix'),
				'severity' => 'low',
				'details' => (string) ($res['error'] ?? 'inspect_failed'),
			]];
		}

		$alerts = [];
		foreach ($res['results'] as $r) {
			if (!is_array($r)) {
				continue;
			}
			$url = trim((string) ($r['url'] ?? ''));
			$verdict = trim((string) ($r['verdict'] ?? ''));
			$indexing = trim((string) ($r['indexingState'] ?? ''));
			$robots = trim((string) ($r['robotsTxtState'] ?? ''));
			$fetch = trim((string) ($r['pageFetchState'] ?? ''));

			$bad = false;
			if ($verdict !== '' && strtoupper($verdict) !== 'PASS') {
				$bad = true;
			}
			if ($indexing !== '' && stripos($indexing, 'INDEXING_ALLOWED') === false && stripos($indexing, 'INDEXED') === false) {
				$bad = true;
			}
			if ($robots !== '' && stripos($robots, 'ALLOWED') === false) {
				$bad = true;
			}
			if ($fetch !== '' && stripos($fetch, 'SUCCESSFUL') === false) {
				$bad = true;
			}
			if (!$bad) {
				continue;
			}

			$alerts[] = [
				'title' => __('בעיה באינדוקס (GSC)', 'icomm-metrix'),
				'severity' => 'medium',
				'details' => trim($url . ', ' . implode(' · ', array_filter([$verdict, $indexing, $robots, $fetch]))),
			];
		}

		return $alerts;
	}

	/**
	 * @param array<string,mixed> $s
	 * @return string[]
	 */
	private static function recipients(array $s): array {
		$to = [];
		if (!empty($s['alerts_send_admin'])) {
			$admin = get_option('admin_email');
			if (is_string($admin) && is_email($admin)) {
				$to[] = $admin;
			}
		}
		if (!empty($s['alerts_send_client'])) {
			$client = sanitize_email((string) ($s['client_report_email'] ?? ''));
			if ($client !== '' && is_email($client)) {
				$to[] = $client;
			}
		}
		return array_values(array_unique($to));
	}

	/**
	 * @param array<int, array{title:string, severity:string, details:string}> $signals
	 * @param array{clicks:int,impressions:int,sessions:int,users:int,period_days:int} $prev
	 * @param array{clicks:int,impressions:int,sessions:int,users:int,period_days:int} $cur
	 */
	private static function email_html(array $signals, int $period_days, array $prev, array $cur): string {
		$site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$dash = admin_url('admin.php?page=icomm-metrix');
		$connections = admin_url('admin.php?page=icomm-metrix-connections');
		$settings = admin_url('admin.php?page=icomm-metrix-settings');

		$rows = '';
		foreach ($signals as $s) {
			$title = esc_html((string) ($s['title'] ?? ''));
			$details = esc_html((string) ($s['details'] ?? ''));
			$sev = (string) ($s['severity'] ?? 'low');
			$color = $sev === 'critical' ? '#b91c1c' : ($sev === 'high' ? '#c2410c' : '#1d4ed8');
			$rows .= '<tr>'
				. '<td style="padding:10px 12px;border-bottom:1px solid #e5e7eb;"><strong style="color:' . esc_attr($color) . ';">' . $title . '</strong><div style="color:#374151;margin-top:4px;">' . $details . '</div></td>'
				. '</tr>';
		}

		$summary = '<ul style="direction:rtl;text-align:right;padding-right:1.2em;padding-left:0;margin:8px 0 0;">'
			. '<li>' . esc_html(sprintf(__('קליקים: %d → %d', 'icomm-metrix'), (int) $prev['clicks'], (int) $cur['clicks'])) . '</li>'
			. '<li>' . esc_html(sprintf(__('חשיפות: %d → %d', 'icomm-metrix'), (int) $prev['impressions'], (int) $cur['impressions'])) . '</li>'
			. '<li>' . esc_html(sprintf(__('כניסות: %d → %d', 'icomm-metrix'), (int) $prev['sessions'], (int) $cur['sessions'])) . '</li>'
			. '</ul>';

		return '<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8"></head><body dir="rtl" style="direction:rtl;text-align:right;font-family:Arial,Helvetica,sans-serif;margin:0;padding:18px;background:#f6f7f7;">'
			. '<div style="max-width:760px;margin:0 auto;background:#fff;border:1px solid #dcdcde;padding:16px 18px;">'
			. '<h2 style="margin:0 0 8px;">' . esc_html(sprintf(__('התראה, %s', 'icomm-metrix'), $site)) . '</h2>'
			. '<p style="margin:0 0 10px;color:#50575e;">' . esc_html(sprintf(__('השוואה: %d ימים אחרונים מול %d ימים קודמים (עד אתמול).', 'icomm-metrix'), $period_days, $period_days)) . '</p>'
			. $summary
			. '<table role="presentation" style="width:100%;border-collapse:collapse;margin-top:12px;">' . $rows . '</table>'
			. '<p style="margin:14px 0 0;">'
			. '<a href="' . esc_url($dash) . '" style="display:inline-block;padding:10px 14px;background:#2271b1;color:#fff;text-decoration:none;border-radius:4px;">' . esc_html__('פתח דשבורד', 'icomm-metrix') . '</a> '
			. '<a href="' . esc_url($connections) . '" style="display:inline-block;padding:10px 14px;background:#f0f0f1;color:#1d2327;text-decoration:none;border-radius:4px;border:1px solid #c3c4c7;">' . esc_html__('בדיקת חיבורים', 'icomm-metrix') . '</a> '
			. '<a href="' . esc_url($settings) . '" style="display:inline-block;padding:10px 14px;background:#f0f0f1;color:#1d2327;text-decoration:none;border-radius:4px;border:1px solid #c3c4c7;">' . esc_html__('הגדרות התראות', 'icomm-metrix') . '</a>'
			. '</p>'
			. '</div></body></html>';
	}
}

