<?php

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

final class IComm_SM_Admin {

	private const MAX_INSPECT_URLS = 30;
	private const MAX_INDEX_WATCH = 30;

	private static function normalize_host(string $host): string {
		$host = strtolower(trim($host));
		if (strpos($host, 'www.') === 0) {
			$host = substr($host, 4);
		}
		return rtrim($host, '.');
	}

	private static function current_site_host(): string {
		$h = (string) parse_url(home_url('/'), PHP_URL_HOST);
		return self::normalize_host($h);
	}

	private static function gsc_property_host(string $property): string {
		$property = trim((string) $property);
		if ($property === '') {
			return '';
		}
		$low = strtolower($property);
		if (strpos($low, 'sc-domain:') === 0) {
			return self::normalize_host(substr($property, strlen('sc-domain:')));
		}
		if (filter_var($property, FILTER_VALIDATE_URL)) {
			$h = (string) parse_url($property, PHP_URL_HOST);
			return self::normalize_host($h);
		}
		return '';
	}

	private static function normalize_ga4_property_id(string $id): string {
		$id = trim((string) $id);
		if ($id === '') {
			return '';
		}
		if (ctype_digit($id)) {
			return 'properties/' . $id;
		}
		if (preg_match('~^properties/\\d+$~', $id)) {
			return $id;
		}
		return $id;
	}

	public static function init(): void {
		add_action('admin_init', [__CLASS__, 'handle_check_updates_request']);
		add_action('admin_menu', [__CLASS__, 'register_menu']);
		add_action('admin_enqueue_scripts', [__CLASS__, 'enqueue_assets']);
		add_action('admin_post_icomm_sm_save_settings', [__CLASS__, 'handle_save_settings']);
		add_action('admin_post_icomm_sm_save_keywords', [__CLASS__, 'handle_save_keywords']);
		add_action('admin_post_icomm_sm_sync_now', [__CLASS__, 'handle_sync_now']);
		add_action('admin_post_icomm_sm_disconnect', [__CLASS__, 'handle_disconnect']);
		add_action('admin_post_icomm_sm_save_connections', [__CLASS__, 'handle_save_connections']);
		add_action('admin_post_icomm_sm_inspect_urls', [__CLASS__, 'handle_inspect_urls']);
		add_action('admin_post_icomm_sm_save_inspect_list', [__CLASS__, 'handle_save_inspect_list']);
		add_action('admin_post_icomm_sm_remote_diag', [__CLASS__, 'handle_remote_diag']);
		add_action('admin_post_icomm_sm_opp_mark_done', [__CLASS__, 'handle_opp_mark_done']);
		add_action('admin_post_icomm_sm_opp_unmark_done', [__CLASS__, 'handle_opp_unmark_done']);
		add_action('admin_post_icomm_sm_niche_research', [__CLASS__, 'handle_niche_research']);
		add_action('wp_ajax_icomm_sm_niche_research', [__CLASS__, 'handle_niche_research_ajax']);
		add_action('admin_post_icomm_sm_connect', [__CLASS__, 'handle_connect']);
		add_action('admin_post_icomm_sm_send_trend_email', [__CLASS__, 'handle_send_trend_email']);
		add_action('admin_post_icomm_sm_send_client_report', [__CLASS__, 'handle_send_client_report']);
		add_action('admin_post_icomm_sm_download_client_pdf', [__CLASS__, 'handle_download_client_pdf']);
	}

	public static function register_menu(): void {
		add_menu_page(
			__('icomm metrix', 'icomm-metrix'),
			__('icomm metrix', 'icomm-metrix'),
			'manage_options',
			'icomm-metrix',
			[__CLASS__, 'render_dashboard'],
			'dashicons-chart-area',
			57
		);
		add_submenu_page('icomm-metrix', __('דשבורד', 'icomm-metrix'), __('דשבורד', 'icomm-metrix'), 'manage_options', 'icomm-metrix', [__CLASS__, 'render_dashboard']);
		add_submenu_page('icomm-metrix', __('חיבורים', 'icomm-metrix'), __('חיבורים', 'icomm-metrix'), 'manage_options', 'icomm-metrix-connections', [__CLASS__, 'render_connections']);
		add_submenu_page('icomm-metrix', __('דירוגים בגוגל', 'icomm-metrix'), __('דירוגים בגוגל', 'icomm-metrix') . IComm_SM_Features::pro_badge_html(), 'manage_options', 'icomm-metrix-keywords', [__CLASS__, 'render_keywords']);
		add_submenu_page('icomm-metrix', __('הזדמנויות SEO', 'icomm-metrix'), __('הזדמנויות SEO', 'icomm-metrix') . IComm_SM_Features::pro_badge_html(), 'manage_options', 'icomm-metrix-opportunities', [__CLASS__, 'render_opportunities']);
		add_submenu_page('icomm-metrix', __('דוח ללקוח', 'icomm-metrix'), __('דוח ללקוח', 'icomm-metrix') . IComm_SM_Features::pro_badge_html(), 'manage_options', 'icomm-metrix-client', [__CLASS__, 'render_report']);
		add_submenu_page('icomm-metrix', __('הגדרות', 'icomm-metrix'), __('הגדרות', 'icomm-metrix'), 'manage_options', 'icomm-metrix-settings', [__CLASS__, 'render_settings']);
	}

	public static function handle_check_updates_request(): void {
		if (!current_user_can('manage_options')) {
			return;
		}
		if (!isset($_GET['icomm_sm_action']) || (string) wp_unslash($_GET['icomm_sm_action']) !== 'check_updates') {
			return;
		}
		check_admin_referer('icomm_sm_check_updates');
		if (function_exists('wp_clean_plugins_cache')) {
			wp_clean_plugins_cache(true);
		}
		IComm_SM_Updater::bust_cache();
		delete_site_transient('update_plugins');
		if (function_exists('wp_update_plugins')) {
			wp_update_plugins();
		}
		$has_update = 0;
		$t = get_site_transient('update_plugins');
		$plugin_file = plugin_basename(ICOMM_SM_PLUGIN_FILE);
		if (is_object($t) && isset($t->response) && is_array($t->response) && isset($t->response[$plugin_file])) {
			$has_update = 1;
		}
		wp_safe_redirect(
			add_query_arg(
				[
					'icomm_sm_updates_checked' => '1',
					'icomm_sm_has_update' => (string) $has_update,
				],
				admin_url('plugins.php')
			)
		);
		exit;
	}

	public static function enqueue_assets(string $hook): void {
		if (strpos($hook, 'icomm-metrix') === false) {
			return;
		}
		wp_enqueue_style('icomm-sm-admin', ICOMM_SM_PLUGIN_URL . 'admin/css/admin.css', [], ICOMM_SM_VERSION);
		wp_enqueue_script(
			'icomm-sm-admin-busy',
			ICOMM_SM_PLUGIN_URL . 'admin/js/admin-busy.js',
			[],
			ICOMM_SM_VERSION,
			true
		);
		wp_localize_script('icomm-sm-admin-busy', 'icommSmBusy', [
			'ajaxUrl' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('icomm_sm_busy'),
			'defaultTitle' => __('מתבצעת פעולה…', 'icomm-metrix'),
			'working' => __('עובדים…', 'icomm-metrix'),
			'done' => __('הושלם. טוענים תוצאות…', 'icomm-metrix'),
			'error' => __('הפעולה נכשלה. נסו שוב.', 'icomm-metrix'),
			'hint' => __('אל תסגרו ואל תרעננו את העמוד בזמן הסריקה.', 'icomm-metrix'),
			'presets' => [
				'niche' => [
					'title' => __('סורקים תחום…', 'icomm-metrix'),
					'intervalMs' => 2000,
					'steps' => [
						['pct' => 12, 'text' => __('1/4 בודקים שאילתות GSC שקשורות לתחום…', 'icomm-metrix')],
						['pct' => 38, 'text' => __('2/4 אוספים השלמות חיפוש רלוונטיות…', 'icomm-metrix')],
						['pct' => 62, 'text' => __('3/4 ממפים מילים לעמודים באתר…', 'icomm-metrix')],
						['pct' => 88, 'text' => __('4/4 בונים המלצות לשפר / להקים…', 'icomm-metrix')],
					],
				],
				'sync' => [
					'title' => __('מסנכרנים מול Google…', 'icomm-metrix'),
					'intervalMs' => 2500,
					'steps' => [
						['pct' => 15, 'text' => __('1/3 מתחברים לשרת הרישוי…', 'icomm-metrix')],
						['pct' => 45, 'text' => __('2/3 מושכים נתוני Search Console…', 'icomm-metrix')],
						['pct' => 78, 'text' => __('3/3 שומרים מדדים במערכת…', 'icomm-metrix')],
					],
				],
				'inspect' => [
					'title' => __('בודקים אינדוקס…', 'icomm-metrix'),
					'intervalMs' => 3200,
					'steps' => [
						['pct' => 18, 'text' => __('שולחים כתובות לבדיקה מול Google…', 'icomm-metrix')],
						['pct' => 48, 'text' => __('ממתינים לתשובת אינדוקס (יכול לקחת עד כדקה)…', 'icomm-metrix')],
						['pct' => 82, 'text' => __('מעבדים תוצאות…', 'icomm-metrix')],
					],
				],
			],
		]);

		$page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
		if ($page === 'icomm-metrix' && IComm_SM_Features::can_use('seo_trend')) {
			self::enqueue_trend_chart_assets();
		}
	}

	private static function enqueue_trend_chart_assets(): void {
		$trend = IComm_SM_Recommendations::seo_monthly_trend();
		$months = is_array($trend['months'] ?? null) ? $trend['months'] : [];
		if ($months === []) {
			return;
		}
		wp_enqueue_script(
			'icomm-sm-chartjs',
			ICOMM_SM_PLUGIN_URL . 'admin/js/vendor/chart.umd.min.js',
			[],
			'4.4.8',
			true
		);
		wp_enqueue_script(
			'icomm-sm-trend-chart',
			ICOMM_SM_PLUGIN_URL . 'admin/js/admin-trend-chart.js',
			['icomm-sm-chartjs'],
			ICOMM_SM_VERSION,
			true
		);
		wp_localize_script('icomm-sm-trend-chart', 'icommSmTrendChart', [
			'months' => $months,
			'daily' => IComm_SM_DB::daily_seo_series(IComm_SM_Features::trend_history_days()),
			'ohlcClicks' => IComm_SM_DB::monthly_ohlc('clicks', 16),
			'ohlcImpressions' => IComm_SM_DB::monthly_ohlc('impressions', 16),
			'i18n' => [
				'clicks' => __('קליקים', 'icomm-metrix'),
				'impressions' => __('חשיפות', 'icomm-metrix'),
				'rangeDay' => __('טווח יומי בחודש', 'icomm-metrix'),
				'close' => __('סגירה (סוף חודש)', 'icomm-metrix'),
				'candleHint' => __('נרות: הטווח מציג מינימום/מקסימום יומי בתוך החודש. ירוק = סגירה גבוהה מפתיחה, אדום = נמוכה.', 'icomm-metrix'),
				'dailyHint' => __('תצוגת קו יומית מפורטת למדד שנבחר.', 'icomm-metrix'),
				'chartMissing' => __('ספריית הגרפים לא נטענה. רעננו את העמוד.', 'icomm-metrix'),
			],
		]);
	}

	public static function render_dashboard(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/dashboard.php';
	}

	public static function render_connections(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/connections.php';
	}

	public static function render_report(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/report.php';
	}

	public static function render_settings(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/settings.php';
	}

	public static function render_keywords(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/keywords.php';
	}

	public static function render_opportunities(): void {
		self::guard();
		require ICOMM_SM_PLUGIN_DIR . 'admin/views/opportunities.php';
	}

	public static function handle_save_keywords(): void {
		self::guard();
		check_admin_referer('icomm_sm_save_keywords');

		// If feature is locked, just bounce back.
		if (!IComm_SM_Features::can_use('keyword_watch')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-keywords', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}

		$s = IComm_SM_Settings::get();
		$raw = sanitize_textarea_field(wp_unslash($_POST['watch_keywords'] ?? ''));
		$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
		$kws = array_values(array_unique(array_filter(array_map('trim', $lines))));
		$kws = array_slice($kws, 0, IComm_SM_Features::PRO_MAX_WATCH_KEYWORDS);
		$s['watch_keywords'] = $kws;
		IComm_SM_Settings::save($s);

		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-keywords', 'saved' => '1'], admin_url('admin.php')));
		exit;
	}

	public static function handle_save_settings(): void {
		self::guard();
		check_admin_referer('icomm_sm_save_settings');

		$s = IComm_SM_Settings::get();
		$lic = IComm_SM_License::get_settings();

		if (array_key_exists('license_key', $_POST) || array_key_exists('license_key_masked', $_POST)) {
			$prev = trim((string) ($lic['license_key'] ?? ''));
			$submitted = array_key_exists('license_key', $_POST)
				? trim(sanitize_text_field(wp_unslash($_POST['license_key'])))
				: $prev;
			$masked_post = isset($_POST['license_key_masked'])
				? sanitize_text_field((string) wp_unslash($_POST['license_key_masked']))
				: null;
			if ($masked_post !== null) {
				$masked_post = trim((string) $masked_post);
				if ($masked_post === '') {
					$submitted = '';
				} elseif (function_exists('icomm_lic_client_is_masked_license_key')
					&& icomm_lic_client_is_masked_license_key($masked_post, $prev)) {
					$submitted = $prev;
				} elseif ($masked_post !== '' && strpos($masked_post, '*') === false && strpos($masked_post, '•') === false) {
					$submitted = $masked_post;
				}
			}
			if ($submitted === '') {
				$lic['license_key'] = '';
				$lic['license_token'] = '';
				$lic['license_status'] = 'inactive';
				$lic['license_expires_at'] = 0;
			} elseif ($submitted !== $prev) {
				$act = IComm_SM_License::activate_with_server($submitted);
				if (!empty($act['ok'])) {
					$lic['license_key'] = $submitted;
					$lic['license_token'] = (string) $act['token'];
					$lic['license_status'] = 'active';
					$lic['license_expires_at'] = (int) $act['expires_at'];
					$lic['license_last_ok'] = current_time('timestamp');
					$lic['license_last_error'] = '';
				} else {
					$lic['license_key'] = $submitted;
					$lic['license_last_error'] = (string) ($act['error'] ?? 'activation_failed');
				}
			}
			IComm_SM_License::save_settings($lic);
		}

		if (IComm_SM_Features::can_use('client_email')) {
			$s['client_report_email'] = sanitize_email(wp_unslash($_POST['client_report_email'] ?? ''));
			$s['client_report_enabled'] = isset($_POST['client_report_enabled']) ? 1 : 0;
			$s['client_report_day'] = max(1, min(28, (int) ($_POST['client_report_day'] ?? 1)));
		}
		if (IComm_SM_Features::can_use('report_branding')) {
			$s['agency_name'] = sanitize_text_field(wp_unslash($_POST['agency_name'] ?? ''));
			$s['agency_logo_url'] = esc_url_raw(wp_unslash($_POST['agency_logo_url'] ?? ''));
		}
		if (IComm_SM_Features::can_use('keyword_watch') && isset($_POST['watch_keywords'])) {
			$raw = sanitize_textarea_field(wp_unslash($_POST['watch_keywords']));
			$lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
			$s['watch_keywords'] = array_values(array_filter(array_map('trim', $lines)));
		}

		// Alerts (PRO)
		if (IComm_SM_Features::can_use('alerts')) {
			$s['alerts_enabled'] = isset($_POST['alerts_enabled']) ? 1 : 0;
			$s['alerts_send_admin'] = isset($_POST['alerts_send_admin']) ? 1 : 0;
			$s['alerts_send_client'] = isset($_POST['alerts_send_client']) ? 1 : 0;
			$s['alerts_drop_pct'] = max(5, min(95, (int) ($_POST['alerts_drop_pct'] ?? 30)));
			$s['alerts_period_days'] = max(3, min(30, (int) ($_POST['alerts_period_days'] ?? 7)));
			$s['alerts_min_clicks'] = max(0, min(1000000, (int) ($_POST['alerts_min_clicks'] ?? 20)));
		}

		// Index watch (PRO)
		if (IComm_SM_Features::can_use('gsc_indexing')) {
			$s['index_watch_enabled'] = isset($_POST['index_watch_enabled']) ? 1 : 0;
			$s['index_watch_max'] = max(1, min(self::MAX_INDEX_WATCH, (int) ($_POST['index_watch_max'] ?? 5)));
			if (isset($_POST['index_watch_urls'])) {
				$raw_urls = sanitize_textarea_field(wp_unslash($_POST['index_watch_urls']));
				$lines = preg_split('/\r\n|\r|\n/', $raw_urls) ?: [];
				$urls = [];
				$skipped_foreign = 0;
				$site_host = self::current_site_host();
				foreach ($lines as $line) {
					$u = trim((string) $line);
					if ($u === '') {
						continue;
					}
					if (filter_var($u, FILTER_VALIDATE_URL)) {
						$h = (string) parse_url($u, PHP_URL_HOST);
						$h = self::normalize_host($h);
						if ($h !== '' && $site_host !== '' && $h !== $site_host) {
							$skipped_foreign++;
							continue;
						}
						$urls[] = $u;
					}
				}
				$s['index_watch_urls'] = array_values(array_unique($urls));
				if ($skipped_foreign > 0) {
					$s['index_watch_last_skip'] = $skipped_foreign;
				} else {
					$s['index_watch_last_skip'] = 0;
				}
			}
		}

		IComm_SM_Settings::save($s);
		IComm_SM_Cron::schedule_if_needed();

		$args = ['page' => 'icomm-metrix-settings', 'updated' => '1'];
		if (!empty($s['index_watch_last_skip'])) {
			$args['skip_urls'] = (string) (int) $s['index_watch_last_skip'];
		}
		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
		exit;
	}

	/**
	 * Parse inspect textarea into same-site URLs (full list, unique).
	 *
	 * @return string[]
	 */
	private static function parse_inspect_urls_from_raw(string $urls_raw): array {
		$lines = preg_split('/\r\n|\r|\n/', $urls_raw) ?: [];
		$urls = [];
		$site_host = self::current_site_host();
		foreach ($lines as $line) {
			$u = trim((string) $line);
			if ($u === '' || !filter_var($u, FILTER_VALIDATE_URL)) {
				continue;
			}
			$h = self::normalize_host((string) parse_url($u, PHP_URL_HOST));
			if ($h !== '' && $site_host !== '' && $h !== $site_host) {
				continue;
			}
			$urls[] = $u;
		}
		return array_values(array_unique($urls));
	}

	/** Persist inspect list + limit so the form stays filled across visits. */
	private static function persist_inspect_list(string $urls_raw, int $limit, array $urls_parsed): void {
		$limit = max(1, min(self::MAX_INSPECT_URLS, $limit));
		$s = IComm_SM_Settings::get();
		// Keep full typed list (up to max), not only the slice checked this run.
		$s['inspect_saved_urls'] = array_slice($urls_parsed, 0, self::MAX_INSPECT_URLS);
		$s['inspect_limit'] = $limit;
		IComm_SM_Settings::save($s);

		$uid = get_current_user_id();
		if ($uid > 0) {
			set_transient('icomm_sm_last_inspect_input_' . $uid, [
				'raw' => implode("\n", $s['inspect_saved_urls']),
				'limit' => $limit,
				'count' => count($s['inspect_saved_urls']),
			], DAY_IN_SECONDS);
		}
	}

	public static function handle_save_inspect_list(): void {
		self::guard();
		check_admin_referer('icomm_sm_save_inspect_list');
		if (!IComm_SM_Features::can_use('gsc_indexing')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}
		$urls_raw = sanitize_textarea_field(wp_unslash($_POST['inspect_urls'] ?? ''));
		$limit = isset($_POST['inspect_limit']) ? (int) $_POST['inspect_limit'] : 10;
		$urls = self::parse_inspect_urls_from_raw($urls_raw);
		self::persist_inspect_list($urls_raw, $limit, $urls);
		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'inspect_saved' => '1'], admin_url('admin.php')));
		exit;
	}

	public static function handle_inspect_urls(): void {
		self::guard();
		check_admin_referer('icomm_sm_inspect_urls');
		if (!IComm_SM_Features::can_use('gsc_indexing')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}

		// Google URL Inspection is slow per URL; avoid PHP killing the request mid-batch.
		if (function_exists('set_time_limit')) {
			@set_time_limit(180);
		}

		$urls_raw = sanitize_textarea_field(wp_unslash($_POST['inspect_urls'] ?? ''));
		$limit = isset($_POST['inspect_limit']) ? (int) $_POST['inspect_limit'] : 10;
		$limit = max(1, min(self::MAX_INSPECT_URLS, $limit));
		$urls_all = self::parse_inspect_urls_from_raw($urls_raw);
		self::persist_inspect_list($urls_raw, $limit, $urls_all);

		$urls = array_slice($urls_all, 0, $limit);
		$res = $urls !== [] ? IComm_SM_Remote::inspect_urls($urls, $limit) : ['ok' => false, 'error' => 'no_valid_urls'];

		$uid = get_current_user_id();
		if ($uid > 0) {
			set_transient('icomm_sm_last_inspect_' . $uid, $res, 5 * MINUTE_IN_SECONDS);
		}
		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'inspect' => '1'], admin_url('admin.php')));
		exit;
	}

	public static function handle_remote_diag(): void {
		self::guard();
		check_admin_referer('icomm_sm_remote_diag');

		$uid = get_current_user_id();
		$diag = [
			'ok' => false,
			'api_base' => IComm_SM_Remote::api_base(),
			'site' => (string) wp_parse_url(home_url('/'), PHP_URL_HOST),
			'gsc' => IComm_SM_Remote::catalog('search'),
			'ga4' => IComm_SM_Remote::catalog('stats'),
		];
		$diag['ok'] = !empty($diag['gsc']['ok']) || !empty($diag['ga4']['ok']);

		if ($uid > 0) {
			set_transient('icomm_sm_last_remote_diag_' . $uid, $diag, 10 * MINUTE_IN_SECONDS);
		}
		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'diag' => '1'], admin_url('admin.php')));
		exit;
	}

	public static function handle_sync_now(): void {
		self::guard();
		check_admin_referer('icomm_sm_sync_now');
		$result = IComm_SM_Cron::run_sync();
		$s = IComm_SM_Settings::get();
		$s['last_manual_sync_at'] = current_time('timestamp');
		IComm_SM_Settings::save($s);
		$args = ['page' => 'icomm-metrix'];
		if (!empty($result['ok'])) {
			$args['synced'] = '1';
		} else {
			$args['sync_error'] = '1';
		}
		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
		exit;
	}

	public static function handle_send_client_report(): void {
		self::guard();
		check_admin_referer('icomm_sm_send_client_report');
		$period = IComm_SM_Report_Builder::resolve_period_from_request(wp_unslash($_POST));
		$args = array_merge(
			['page' => 'icomm-metrix-client'],
			IComm_SM_Report_Builder::period_query_args($period)
		);
		if (!IComm_SM_Features::can_use('client_email')) {
			$args['client_mail'] = 'locked';
			wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
			exit;
		}
		$to = isset($_POST['client_mail_to']) ? sanitize_email(wp_unslash((string) $_POST['client_mail_to'])) : '';
		$res = IComm_SM_Report_Builder::send_monthly_email($to, $period);
		if (!empty($res['ok'])) {
			$args['client_mail'] = 'ok';
		} else {
			$args['client_mail'] = 'err';
			$args['client_mail_err'] = sanitize_key((string) ($res['error'] ?? 'send_failed'));
			if (!empty($res['detail'])) {
				set_transient(
					'icomm_sm_client_mail_err_' . get_current_user_id(),
					(string) $res['detail'],
					5 * MINUTE_IN_SECONDS
				);
			}
		}
		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
		exit;
	}

	public static function handle_download_client_pdf(): void {
		self::guard();
		check_admin_referer('icomm_sm_download_client_pdf');
		if (!IComm_SM_Features::can_use('client_pdf')) {
			wp_die(esc_html__('הורדת PDF זמינה ב-PRO.', 'icomm-metrix'));
		}
		$period = IComm_SM_Report_Builder::previous_month_period();
		$res = IComm_SM_Pdf::render_monthly_report($period);
		if (empty($res['ok']) || empty($res['pdf'])) {
			$msg = __('יצירת PDF נכשלה.', 'icomm-metrix');
			if (!empty($res['detail'])) {
				$msg .= ' ' . (string) $res['detail'];
			}
			wp_die(esc_html($msg));
		}
		$filename = (string) ($res['filename'] ?? 'icomm-metrix-report.pdf');
		nocache_headers();
		header('Content-Type: application/pdf');
		header('Content-Disposition: attachment; filename="' . $filename . '"');
		header('Content-Length: ' . (string) strlen((string) $res['pdf']));
		echo $res['pdf']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	public static function handle_send_trend_email(): void {
		self::guard();
		check_admin_referer('icomm_sm_send_trend_email');
		$args = ['page' => 'icomm-metrix'];
		if (!IComm_SM_Features::can_use('seo_trend')) {
			$args['trend_mail'] = 'locked';
			wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
			exit;
		}

		$to = isset($_POST['trend_mail_to']) ? sanitize_email(wp_unslash((string) $_POST['trend_mail_to'])) : '';
		$include = !empty($_POST['trend_mail_analysis']);
		$do_preview = !empty($_POST['trend_mail_preview']);

		if ($do_preview) {
			nocache_headers();
			header('Content-Type: text/html; charset=UTF-8');
			$html = IComm_SM_Report_Builder::trend_email_html($include);
			echo '<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
				. '<title>' . esc_html__('תצוגה מקדימה - מגמת SEO', 'icomm-metrix') . '</title>'
				. '<style type="text/css">body,table,td,th,p,span,strong,h1,h2{font-family:Arial,Helvetica,sans-serif !important;}body{margin:0;padding:0;background:#f0f0f1;}</style>'
				. '</head>'
				. '<body dir="rtl" style="direction:rtl;text-align:right;margin:0;padding:0;background:#f0f0f1;font-family:Arial,Helvetica,sans-serif;font-size:12pt;">'
				. $html
				. '<p style="max-width:680px;margin:12px auto 24px;padding:0 12px;font-family:Arial,Helvetica,sans-serif;font-size:12pt;color:#50575e;text-align:center;">'
				. esc_html__('זו תצוגה מקדימה בלבד. המייל עדיין לא נשלח.', 'icomm-metrix')
				. '</p></body></html>';
			exit;
		}

		$res = IComm_SM_Report_Builder::send_trend_email($to, $include);
		if (!empty($res['ok'])) {
			$args['trend_mail'] = 'ok';
		} else {
			$args['trend_mail'] = 'err';
			$args['trend_mail_err'] = sanitize_key((string) ($res['error'] ?? 'send_failed'));
			if (!empty($res['detail'])) {
				set_transient(
					'icomm_sm_trend_mail_err_' . get_current_user_id(),
					(string) $res['detail'],
					5 * MINUTE_IN_SECONDS
				);
			}
		}
		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')));
		exit;
	}

	public static function handle_connect(): void {
		self::guard();
		$service = isset($_GET['service']) ? sanitize_key(wp_unslash($_GET['service'])) : '';
		check_admin_referer('icomm_sm_connect_' . $service);
		$url = IComm_SM_Remote::mint_connect_redirect($service);
		if ($url === '') {
			wp_safe_redirect(add_query_arg([
				'page' => 'icomm-metrix-connections',
				'icomm_sm_msg' => 'connect_failed',
			], admin_url('admin.php')));
			exit;
		}
		// License server / Google OAuth (external).
		wp_redirect($url);
		exit;
	}

	public static function handle_disconnect(): void {
		self::guard();
		$service = isset($_GET['service']) ? sanitize_key(wp_unslash($_GET['service'])) : '';
		check_admin_referer('icomm_sm_disconnect_' . $service);
		IComm_SM_Remote::disconnect($service);
		$s = IComm_SM_Settings::get();
		if ($service === 'search' || $service === 'gsc') {
			$s['gsc_connected'] = 0;
			$s['gsc_property'] = '';
			$s['gsc_last_error'] = '';
		} elseif ($service === 'stats' || $service === 'ga4') {
			$s['ga4_connected'] = 0;
			$s['ga4_property_id'] = '';
			$s['ga4_last_error'] = '';
		}
		IComm_SM_Settings::save($s);
		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'icomm_sm_msg' => 'disconnected'], admin_url('admin.php')));
		exit;
	}

	public static function handle_save_connections(): void {
		self::guard();
		check_admin_referer('icomm_sm_save_connections');

		$gsc = !empty($_POST['gsc_property']) ? sanitize_text_field(wp_unslash($_POST['gsc_property'])) : '';
		$s = IComm_SM_Settings::get();
		$ga4 = !empty($_POST['ga4_property_id']) ? self::normalize_ga4_property_id(sanitize_text_field(wp_unslash($_POST['ga4_property_id']))) : '';

		// Convenience: if user pasted just a domain (example.com), treat it as sc-domain:example.com.
		if ($gsc !== '') {
			$gsc_trim = trim($gsc);
			$low = strtolower($gsc_trim);
			if (strpos($low, 'sc-domain:') !== 0 && !filter_var($gsc_trim, FILTER_VALIDATE_URL)) {
				$hostish = self::normalize_host($gsc_trim);
				if (strpos($hostish, '.') !== false) {
					$gsc = 'sc-domain:' . $hostish;
				}
			}
		}

		$gsc_ok = true;
		$ga4_ok = true;

		if ($gsc !== '') {
			$site_host = self::current_site_host();
			$prop_host = self::gsc_property_host($gsc);
			if ($prop_host === '') {
				$gsc_ok = false;
				$s['gsc_last_error'] = __('ערך ה-Property לא תקין. דוגמה: sc-domain:example.com או https://www.example.com/', 'icomm-metrix');
			}
			if ($prop_host !== '' && $site_host !== '' && $prop_host !== $site_host) {
				$gsc_ok = false;
				$s['gsc_last_error'] = __('ה-Property שבחרתם שייך לדומיין אחר. בחרו Property של האתר הנוכחי בלבד.', 'icomm-metrix');
			} else {
				$catalog = IComm_SM_Remote::catalog('search');
				$sites = (!empty($catalog['ok']) && !empty($catalog['sites']) && is_array($catalog['sites'])) ? array_map('strval', $catalog['sites']) : [];
				if ($sites !== [] && !in_array($gsc, $sites, true)) {
					// Friendly fallback: user pasted a URL-prefix property, but the account has sc-domain.
					$host = self::normalize_host((string) wp_parse_url($gsc, PHP_URL_HOST));
					$sc_domain = $host !== '' ? ('sc-domain:' . $host) : '';
					if ($sc_domain !== '' && in_array($sc_domain, $sites, true)) {
						$gsc = $sc_domain;
						$gsc_ok = true;
						$s['gsc_last_error'] = '';
					} else {
						$gsc_ok = false;
						$s['gsc_last_error'] = __('ה-Property לא נמצא בחשבון המחובר. התחברו מחדש או בחרו Property מהרשימה.', 'icomm-metrix');
					}
				} elseif (empty($catalog['ok'])) {
					$gsc_ok = false;
					$s['gsc_last_error'] = __('אין הרשאה ל-GSC או שהחיבור לא הושלם. לחצו “חבר נתוני חיפוש” ואז נסו שוב.', 'icomm-metrix');
				} else {
					$s['gsc_last_error'] = '';
				}
			}
		}

		if ($ga4 !== '' && IComm_SM_Features::can_use('ga4_connect')) {
			$catalog = IComm_SM_Remote::catalog('stats');
			$props = (!empty($catalog['ok']) && !empty($catalog['properties']) && is_array($catalog['properties'])) ? $catalog['properties'] : [];
			$ids = [];
			foreach ($props as $p) {
				if (is_array($p) && isset($p['id'])) {
					$ids[] = (string) $p['id'];
				}
			}
			if ($ids !== [] && !in_array($ga4, $ids, true)) {
				$ga4_ok = false;
				$s['ga4_last_error'] = __('נכס GA4 לא נמצא בחשבון המחובר. התחברו מחדש או בחרו נכס מהרשימה.', 'icomm-metrix');
			} elseif (empty($catalog['ok'])) {
				$ga4_ok = false;
				$s['ga4_last_error'] = __('אין הרשאה ל-GA4 או שהחיבור לא הושלם. לחצו “חבר אנליטיקס” ואז נסו שוב.', 'icomm-metrix');
			} else {
				$s['ga4_last_error'] = '';
			}
		}

		if (($gsc !== '' && $gsc_ok) || ($ga4 !== '' && $ga4_ok)) {
			$remote = IComm_SM_Remote::save_property($gsc_ok ? $gsc : '', $ga4_ok ? $ga4 : '');
			if (empty($remote['ok'])) {
				$err = (string) ($remote['error'] ?? 'save_failed');
				if ($err === 'property_domain_mismatch') {
					$err = __('ה-Property שנבחר לא שייך לדומיין של האתר הזה. בחרו רק Property של הדומיין הנוכחי.', 'icomm-metrix');
				}
				if ($gsc !== '' && $gsc_ok) {
					$gsc_ok = false;
					$s['gsc_connected'] = 0;
					$s['gsc_property'] = '';
					$s['gsc_last_error'] = $err;
				}
				if ($ga4 !== '' && $ga4_ok) {
					$ga4_ok = false;
					$s['ga4_connected'] = 0;
					$s['ga4_property_id'] = '';
					$s['ga4_last_error'] = $err;
				}
			}
		}

		if ($gsc !== '' && $gsc_ok) {
			$s['gsc_property'] = $gsc;
			$s['gsc_connected'] = 1;
			delete_transient('icomm_sm_gsc_site_pick');
		}
		if ($ga4 !== '' && $ga4_ok) {
			$s['ga4_property_id'] = $ga4;
			$s['ga4_connected'] = 1;
			delete_transient('icomm_sm_ga4_property_pick');
		}
		IComm_SM_Settings::save($s);

		if (IComm_SM_Settings::is_gsc_ready() || (IComm_SM_Features::can_use('ga4_metrics') && IComm_SM_Settings::is_ga4_ready())) {
			IComm_SM_Cron::run_sync();
		}
		wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-connections', 'updated' => '1'], admin_url('admin.php')));
		exit;
	}

	public static function handle_niche_research(): void {
		self::guard();
		check_admin_referer('icomm_sm_niche_research');
		if (!IComm_SM_Features::can_use('opportunities') && !IComm_SM_Features::can_use('recommendations')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-opportunities', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}
		$topic = sanitize_text_field(wp_unslash($_POST['niche_topic'] ?? ''));
		$result = IComm_SM_Niche_Research::research($topic);
		$args = ['page' => 'icomm-metrix-opportunities'];
		if (!empty($result['ok'])) {
			$args['niche_ok'] = '1';
		} else {
			$args['niche_err'] = sanitize_key((string) ($result['error'] ?? 'fail'));
		}
		wp_safe_redirect(add_query_arg($args, admin_url('admin.php')) . '#icomm-sm-niche');
		exit;
	}

	public static function handle_niche_research_ajax(): void {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => __('Unauthorized', 'icomm-metrix')], 403);
		}
		check_ajax_referer('icomm_sm_niche_research');
		if (!IComm_SM_Features::can_use('opportunities') && !IComm_SM_Features::can_use('recommendations')) {
			wp_send_json_error(['message' => __('נדרש רישיון PRO או תקופת ניסיון.', 'icomm-metrix')], 403);
		}
		@set_time_limit(120);
		$topic = sanitize_text_field(wp_unslash($_POST['niche_topic'] ?? ''));
		$result = IComm_SM_Niche_Research::research($topic);
		$args = ['page' => 'icomm-metrix-opportunities'];
		if (!empty($result['ok'])) {
			$args['niche_ok'] = '1';
			wp_send_json_success([
				'redirect' => add_query_arg($args, admin_url('admin.php')) . '#icomm-sm-niche',
				'summary' => $result['summary'] ?? [],
			]);
		}
		$err = sanitize_key((string) ($result['error'] ?? 'fail'));
		$msg = __('לא ניתן להריץ מחקר תחום כרגע.', 'icomm-metrix');
		if ($err === 'empty' || $err === 'short') {
			$msg = __('כתבו תחום או נושא עסקי (לפחות 2 תווים).', 'icomm-metrix');
		} elseif ($err === 'rate') {
			$msg = __('המתינו כמה שניות לפני מחקר נוסף.', 'icomm-metrix');
		} elseif ($err === 'locked') {
			$msg = __('נדרש רישיון PRO או תקופת ניסיון.', 'icomm-metrix');
		}
		wp_send_json_error(['message' => $msg, 'code' => $err]);
	}

	public static function handle_opp_mark_done(): void {
		self::guard();
		check_admin_referer('icomm_sm_opp_mark_done');
		if (!IComm_SM_Features::can_use('opportunities') && !IComm_SM_Features::can_use('recommendations')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-opportunities', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}
		$query = sanitize_text_field(wp_unslash($_POST['opp_query'] ?? ''));
		$item = [
			'query' => $query,
			'action' => sanitize_key(wp_unslash($_POST['opp_action'] ?? '')),
			'action_label' => sanitize_text_field(wp_unslash($_POST['opp_action_label'] ?? '')),
			'impressions' => (int) ($_POST['opp_impressions'] ?? 0),
			'clicks' => (int) ($_POST['opp_clicks'] ?? 0),
			'ctr' => (float) ($_POST['opp_ctr'] ?? 0),
			'position' => (float) ($_POST['opp_position'] ?? 0),
			'post_id' => (int) ($_POST['opp_post_id'] ?? 0),
			'edit_url' => esc_url_raw(wp_unslash($_POST['opp_edit_url'] ?? '')),
			'view_url' => esc_url_raw(wp_unslash($_POST['opp_view_url'] ?? '')),
		];
		$ok = IComm_SM_Recommendations::mark_opportunity_done($item);
		wp_safe_redirect(add_query_arg([
			'page' => 'icomm-metrix-opportunities',
			'opp_marked' => $ok ? '1' : '0',
		], admin_url('admin.php')));
		exit;
	}

	public static function handle_opp_unmark_done(): void {
		self::guard();
		check_admin_referer('icomm_sm_opp_unmark_done');
		if (!IComm_SM_Features::can_use('opportunities') && !IComm_SM_Features::can_use('recommendations')) {
			wp_safe_redirect(add_query_arg(['page' => 'icomm-metrix-opportunities', 'locked' => '1'], admin_url('admin.php')));
			exit;
		}
		$query = sanitize_text_field(wp_unslash($_POST['opp_query'] ?? ''));
		$ok = IComm_SM_Recommendations::unmark_opportunity_done($query);
		wp_safe_redirect(add_query_arg([
			'page' => 'icomm-metrix-opportunities',
			'opp_unmarked' => $ok ? '1' : '0',
		], admin_url('admin.php')));
		exit;
	}

	private static function guard(): void {
		if (!current_user_can('manage_options')) {
			wp_die(esc_html__('Unauthorized', 'icomm-metrix'));
		}
	}
}
