<?php
if (!defined('ABSPATH')) {
	exit;
}
$s = IComm_SM_Settings::get();
$msg = isset($_GET['icomm_sm_msg']) ? sanitize_key(wp_unslash($_GET['icomm_sm_msg'])) : '';
$auth_service = isset($_GET['icomm_sm_service']) ? sanitize_key(wp_unslash($_GET['icomm_sm_service'])) : '';
if ($msg === 'auth_ok' && $auth_service !== '') {
	$s = IComm_SM_Settings::get();
	if ($auth_service === 'gsc') {
		$s['gsc_connected'] = 1;
		$s['gsc_last_error'] = '';
	} elseif ($auth_service === 'ga4') {
		$s['ga4_connected'] = 1;
		$s['ga4_last_error'] = '';
	}
	IComm_SM_Settings::save($s);
	IComm_SM_Cron::run_sync();
}
$gsc_pick = get_transient('icomm_sm_gsc_site_pick');
$ga4_pick = get_transient('icomm_sm_ga4_property_pick');
if (!is_array($gsc_pick)) {
	$gsc_pick = [];
}
if (!is_array($ga4_pick)) {
	$ga4_pick = [];
}
if ($msg === 'auth_ok' && $gsc_pick === [] && empty($s['gsc_property']) && !empty($s['gsc_connected'])) {
	$catalog = IComm_SM_Remote::catalog('search');
	if (!empty($catalog['ok']) && !empty($catalog['sites']) && is_array($catalog['sites'])) {
		$gsc_pick = $catalog['sites'];
		set_transient('icomm_sm_gsc_site_pick', $gsc_pick, HOUR_IN_SECONDS);
	}
}
if ($msg === 'auth_ok' && $ga4_pick === [] && IComm_SM_Features::can_use('ga4_connect')) {
	$catalog = IComm_SM_Remote::catalog('stats');
	if (!empty($catalog['ok']) && !empty($catalog['properties']) && is_array($catalog['properties'])) {
		$ga4_pick = $catalog['properties'];
		set_transient('icomm_sm_ga4_property_pick', $ga4_pick, HOUR_IN_SECONDS);
	}
}

// Filter GSC properties for current site first (Google returns all properties available to the account).
$normalize_host = static function (string $host): string {
	$host = strtolower(trim($host));
	if (strpos($host, 'www.') === 0) {
		$host = substr($host, 4);
	}
	return rtrim($host, '.');
};
$site_host = $normalize_host((string) parse_url(home_url('/'), PHP_URL_HOST));
$gsc_pick_site = [];
$gsc_pick_other = [];
if (is_array($gsc_pick) && $gsc_pick !== [] && $site_host !== '') {
	foreach ($gsc_pick as $prop) {
		$prop = (string) $prop;
		$prop_trim = trim($prop);
		$prop_host = '';
		if (stripos($prop_trim, 'sc-domain:') === 0) {
			$prop_host = $normalize_host(substr($prop_trim, strlen('sc-domain:')));
		} elseif (filter_var($prop_trim, FILTER_VALIDATE_URL)) {
			$prop_host = $normalize_host((string) parse_url($prop_trim, PHP_URL_HOST));
		}
		if ($prop_host !== '' && $prop_host === $site_host) {
			$gsc_pick_site[] = $prop;
		} else {
			$gsc_pick_other[] = $prop;
		}
	}
}
?>
<div class="wrap icomm-sm-wrap" dir="rtl" lang="he">
	<h1><?php esc_html_e('חיבורים', 'icomm-metrix'); ?> <span>v<?php echo esc_html(ICOMM_SM_VERSION); ?></span></h1>

	<?php if (!empty($_GET['updated'])) : ?>
		<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('נשמר.', 'icomm-metrix'); ?></p></div>
	<?php endif; ?>
	<?php if ($msg === 'auth_ok') : ?>
		<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('החיבור הצליח. בחרו נכס אם נדרש.', 'icomm-metrix'); ?></p></div>
	<?php elseif ($msg === 'auth_denied') : ?>
		<div class="notice notice-warning is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('החיבור בוטל.', 'icomm-metrix'); ?></p></div>
	<?php elseif ($msg === 'auth_error' || $msg === 'auth_state_invalid') : ?>
		<div class="notice notice-error is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('שגיאה בחיבור, נסו שוב.', 'icomm-metrix'); ?></p></div>
	<?php elseif ($msg === 'disconnected') : ?>
		<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('החיבור נותק.', 'icomm-metrix'); ?></p></div>
	<?php elseif ($msg === 'connect_failed') : ?>
		<div class="notice notice-error is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('לא ניתן להתחיל חיבור לגוגל. נסו שוב בעוד רגע.', 'icomm-metrix'); ?></p></div>
	<?php endif; ?>

	<p class="description"><?php esc_html_e('החיבור מתבצע דרך שרת icomm המאובטח, אין צורך בהגדרת API מקומית.', 'icomm-metrix'); ?></p>

	<?php
	$uid = get_current_user_id();
	$diag = (!empty($_GET['diag']) && (string) $_GET['diag'] === '1' && $uid > 0) ? get_transient('icomm_sm_last_remote_diag_' . $uid) : false;
	if (is_array($diag)) :
		$gsc_ok = !empty($diag['gsc']['ok']);
		$ga4_ok = !empty($diag['ga4']['ok']);
		$box_class = ($gsc_ok || $ga4_ok) ? 'notice notice-success' : 'notice notice-error';
		$gsc_err = is_array($diag['gsc']) && !empty($diag['gsc']['error']) ? (string) $diag['gsc']['error'] : '';
		$ga4_err = is_array($diag['ga4']) && !empty($diag['ga4']['error']) ? (string) $diag['ga4']['error'] : '';
		?>
		<div class="<?php echo esc_attr($box_class); ?>" dir="rtl" lang="he" style="direction:rtl;text-align:right;">
			<p style="margin:0 0 6px;"><strong><?php esc_html_e('אבחון חיבור', 'icomm-metrix'); ?></strong></p>
			<p style="margin:0 0 6px;">
				<?php echo esc_html(sprintf(__('אתר: %s', 'icomm-metrix'), (string) ($diag['site'] ?? ''))); ?><br>
				<?php echo esc_html(sprintf(__('API: %s', 'icomm-metrix'), (string) ($diag['api_base'] ?? ''))); ?>
			</p>
			<p style="margin:0;">
				<strong><?php esc_html_e('GSC:', 'icomm-metrix'); ?></strong>
				<?php echo $gsc_ok ? '<span style="color:#15803d;font-weight:600;">OK</span>' : '<span style="color:#b91c1c;font-weight:600;">FAIL</span>'; ?>
				<?php if (!$gsc_ok && $gsc_err !== '') : ?>
					<span class="description" style="display:block;margin-top:4px;"><?php echo esc_html($gsc_err); ?></span>
				<?php endif; ?>
			</p>
			<p style="margin:6px 0 0;">
				<strong><?php esc_html_e('GA4:', 'icomm-metrix'); ?></strong>
				<?php echo $ga4_ok ? '<span style="color:#15803d;font-weight:600;">OK</span>' : '<span style="color:#b91c1c;font-weight:600;">FAIL</span>'; ?>
				<?php if (!$ga4_ok && $ga4_err !== '') : ?>
					<span class="description" style="display:block;margin-top:4px;"><?php echo esc_html($ga4_err); ?></span>
				<?php endif; ?>
			</p>
		</div>
	<?php endif; ?>

	<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he" style="margin:10px 0 18px;">
		<?php wp_nonce_field('icomm_sm_remote_diag'); ?>
		<input type="hidden" name="action" value="icomm_sm_remote_diag" />
		<?php submit_button(__('בדיקת חיבור לשרת icomm (אבחון)', 'icomm-metrix'), 'secondary', 'submit', false); ?>
	</form>

	<?php if (!empty($_GET['inspect_saved'])) : ?>
		<div class="notice notice-success is-dismissible" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p><?php esc_html_e('רשימת ה־URL נשמרה. היא תיטען אוטומטית בפעם הבאה.', 'icomm-metrix'); ?></p></div>
	<?php endif; ?>

	<h2><?php esc_html_e('בדיקת אינדוקס (GSC)', 'icomm-metrix'); ?> <?php echo IComm_SM_Features::pro_badge_html(); ?></h2>
	<?php echo IComm_SM_Features::locked_notice_html(__('בדיקת אינדוקס (GSC)', 'icomm-metrix')); ?>
	<div class="<?php echo IComm_SM_Features::can_use('gsc_indexing') ? '' : 'icomm-sm-locked-preview'; ?>">
		<?php
		$inspect_max = 30;
		$saved_urls = array_values(array_filter(array_map('strval', (array) ($s['inspect_saved_urls'] ?? []))));
		$prefill_inspect = implode("\n", $saved_urls);
		$prefill_limit = max(1, min($inspect_max, (int) ($s['inspect_limit'] ?? 10)));
		$prefill_count = count($saved_urls);
		// Transient wins only right after a check (same request cycle), then settings remain source of truth.
		$uid = get_current_user_id();
		if ($uid > 0 && !empty($_GET['inspect'])) {
			$inspect_input = get_transient('icomm_sm_last_inspect_input_' . $uid);
			if (is_array($inspect_input) && !empty($inspect_input['raw'])) {
				$prefill_inspect = (string) $inspect_input['raw'];
				$prefill_limit = isset($inspect_input['limit']) ? (int) $inspect_input['limit'] : $prefill_limit;
				$prefill_count = isset($inspect_input['count']) ? (int) $inspect_input['count'] : $prefill_count;
			}
		}
		$recent = get_posts([
			'post_type' => ['page', 'post'],
			'posts_per_page' => 50,
			'post_status' => 'publish',
			'orderby' => 'modified',
			'order' => 'DESC',
			'no_found_rows' => true,
		]);
		?>
		<p class="description"><?php echo esc_html(sprintf(__('הדביקו עד %d כתובות (URL) מהאתר הנוכחי בלבד, שורה לכל כתובת, וקבלו סטטוס אינדוקס בסיסי מתוך Google. הרשימה נשמרת אוטומטית אחרי בדיקה או «שמור רשימה».', 'icomm-metrix'), (int) $inspect_max)); ?></p>
		<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he" style="max-width:860px;" id="icomm_sm_inspect_form">
			<?php wp_nonce_field('icomm_sm_inspect_urls'); ?>
			<input type="hidden" name="action" id="icomm_sm_inspect_action" value="icomm_sm_inspect_urls" />
			<input type="hidden" name="_wpnonce_save_list" id="icomm_sm_inspect_save_nonce" value="<?php echo esc_attr(wp_create_nonce('icomm_sm_save_inspect_list')); ?>" />
			<textarea name="inspect_urls" id="icomm_sm_inspect_urls" rows="5" class="large-text" dir="ltr" placeholder="https://example.com/&#10;https://example.com/page/"><?php echo esc_textarea($prefill_inspect); ?></textarea>
			<p class="description" style="margin:6px 0 0;">
				<strong><?php esc_html_e('ברשימה:', 'icomm-metrix'); ?></strong>
				<span id="icomm_sm_inspect_count"><?php echo esc_html((string) max(0, $prefill_count)); ?></span>
				<?php esc_html_e('URL-ים', 'icomm-metrix'); ?>
				· <?php esc_html_e('נשמרת בין ביקורים', 'icomm-metrix'); ?>
			</p>
			<p style="margin:10px 0 0;">
				<label style="margin-left:12px;">
					<?php esc_html_e('כמה לבדוק עכשיו', 'icomm-metrix'); ?>
					<input type="number" name="inspect_limit" min="1" max="<?php echo esc_attr((string) $inspect_max); ?>" value="<?php echo esc_attr((string) max(1, min($inspect_max, $prefill_limit))); ?>" class="small-text" />
				</label>
				<span class="description"><?php esc_html_e('יותר URL-ים = יותר זמן ועשוי לפגוע בקווטה של Google.', 'icomm-metrix'); ?></span>
			</p>
			<?php if (is_array($recent) && $recent !== []) : ?>
				<p style="margin:10px 0 0;">
					<label for="icomm_sm_pick_url_inspect" style="display:inline-block;min-width:120px;"><?php esc_html_e('הוספה מהירה מהאתר', 'icomm-metrix'); ?></label>
					<select id="icomm_sm_pick_url_inspect" dir="ltr" style="min-width:420px;max-width:100%;">
						<option value=""><?php esc_html_e('- בחרו דף/פוסט להוספה לרשימה -', 'icomm-metrix'); ?></option>
						<?php foreach ($recent as $p) : ?>
							<?php
							if (!is_object($p)) { continue; }
							$u = get_permalink($p);
							if (!is_string($u) || $u === '') { continue; }
							$title = get_the_title($p);
							$label = ($title !== '' ? $title : ('#' . (int) $p->ID)) . ', ' . $u;
							?>
							<option value="<?php echo esc_attr($u); ?>"><?php echo esc_html($label); ?></option>
						<?php endforeach; ?>
					</select>
					<button type="button" class="button" id="icomm_sm_add_url_inspect"><?php esc_html_e('הוסף', 'icomm-metrix'); ?></button>
				</p>
			<?php endif; ?>
			<p style="margin-top:10px;">
				<?php
				submit_button(
					__('בדוק אינדוקס', 'icomm-metrix'),
					'secondary',
					'icomm_sm_inspect_go',
					false,
					['id' => 'icomm_sm_inspect_submit']
				);
				?>
				<button type="submit" class="button" id="icomm_sm_save_inspect_list" style="margin-right:8px;"><?php esc_html_e('שמור רשימה', 'icomm-metrix'); ?></button>
			</p>
			<p id="icomm_sm_inspect_status" class="description" style="display:none;margin:8px 0 0;color:#1d2327;font-weight:600;" aria-live="polite"></p>
		</form>
		<script>
		(function(){
			var sel = document.getElementById('icomm_sm_pick_url_inspect');
			var btn = document.getElementById('icomm_sm_add_url_inspect');
			var ta = document.getElementById('icomm_sm_inspect_urls');
			var out = document.getElementById('icomm_sm_inspect_count');
			var form = document.getElementById('icomm_sm_inspect_form');
			var action = document.getElementById('icomm_sm_inspect_action');
			var saveBtn = document.getElementById('icomm_sm_save_inspect_list');
			var saveNonce = document.getElementById('icomm_sm_inspect_save_nonce');
			var checkBtn = document.getElementById('icomm_sm_inspect_submit');
			var statusEl = document.getElementById('icomm_sm_inspect_status');
			var nonceInput = form ? form.querySelector('input[name="_wpnonce"]') : null;
			var inspectNonceVal = nonceInput ? String(nonceInput.value || '') : '';
			var saveNonceVal = saveNonce ? String(saveNonce.value || '') : '';

			function updateCount() {
				if (!ta || !out) { return; }
				var v = (ta.value || '').trim();
				if (!v) { out.textContent = '0'; return; }
				var lines = v.split(/\r\n|\r|\n/).map(function(x){ return (x || '').trim(); }).filter(Boolean);
				var uniq = {};
				lines.forEach(function(x){ uniq[x] = 1; });
				out.textContent = String(Object.keys(uniq).length);
			}
			function setBusy(msg) {
				if (statusEl) {
					statusEl.textContent = msg || '';
					statusEl.style.display = msg ? '' : 'none';
				}
				if (checkBtn) { checkBtn.disabled = true; }
				if (saveBtn) { saveBtn.disabled = true; }
			}
			function nativeSubmit() {
				if (!form) { return; }
				HTMLFormElement.prototype.submit.call(form);
			}
			if (btn && sel && ta) {
				btn.addEventListener('click', function(){
					var u = (sel.value || '').trim();
					if (!u) { return; }
					var cur = (ta.value || '').trim();
					var lines = cur ? cur.split(/\r\n|\r|\n/) : [];
					if (lines.indexOf(u) === -1) { lines.push(u); }
					ta.value = lines.join("\n").trim() + "\n";
					sel.value = '';
					updateCount();
				});
			}
			if (ta) { ta.addEventListener('input', updateCount); updateCount(); }
			if (saveBtn && form && action) {
				saveBtn.addEventListener('click', function(e){
					e.preventDefault();
					action.value = 'icomm_sm_save_inspect_list';
					if (nonceInput && saveNonceVal) { nonceInput.value = saveNonceVal; }
					setBusy(<?php echo wp_json_encode(__('שומרים רשימה…', 'icomm-metrix')); ?>);
					nativeSubmit();
				});
			}
			if (checkBtn && form && action) {
				checkBtn.addEventListener('click', function(){
					// Restore inspect action/nonce if Save mutated them earlier.
					// Do not disable here: disabling the submitter in click can cancel native submit.
					action.value = 'icomm_sm_inspect_urls';
					if (nonceInput && inspectNonceVal) { nonceInput.value = inspectNonceVal; }
				});
			}
			if (form) {
				form.addEventListener('submit', function(){
					if (action && action.value === 'icomm_sm_inspect_urls') {
						setBusy(<?php echo wp_json_encode(__('בודקים אינדוקס מול Google… זה עשוי להימשך עד כדקה. אל תסגרו את העמוד.', 'icomm-metrix')); ?>);
					}
				});
			}
		})();
		</script>
		<?php
		if (!empty($_GET['inspect']) && (string) $_GET['inspect'] === '1') {
			$uid = get_current_user_id();
			$data = $uid > 0 ? get_transient('icomm_sm_last_inspect_' . $uid) : false;
			if (is_array($data) && !empty($data['results']) && is_array($data['results'])) {
				echo '<div style="margin-top:12px;background:#fff;border:1px solid #c3c4c7;padding:12px 14px;">';
				echo '<p style="margin:0 0 10px;"><strong>' . esc_html__('תוצאות בדיקה', 'icomm-metrix') . '</strong></p>';
				echo '<table class="widefat striped" dir="rtl" lang="he"><thead><tr>';
				echo '<th>' . esc_html__('URL', 'icomm-metrix') . '</th>';
				echo '<th>' . esc_html__('Verdict', 'icomm-metrix') . '</th>';
				echo '<th>' . esc_html__('Indexing', 'icomm-metrix') . '</th>';
				echo '<th>' . esc_html__('Robots', 'icomm-metrix') . '</th>';
				echo '<th>' . esc_html__('Fetch', 'icomm-metrix') . '</th>';
				echo '</tr></thead><tbody>';
				foreach ($data['results'] as $r) {
					if (!is_array($r)) {
						continue;
					}
					$url = (string) ($r['url'] ?? '');
					$row_err = (string) ($r['error'] ?? '');
					$verdict = $row_err !== '' ? $row_err : (string) ($r['verdict'] ?? '');
					$indexing = (string) ($r['indexingState'] ?? '');
					$robots = (string) ($r['robotsTxtState'] ?? '');
					$fetch = (string) ($r['pageFetchState'] ?? '');
					$bad = $row_err !== '' || ($verdict !== '' && strtoupper($verdict) !== 'PASS');
					$st = $bad ? 'color:#b91c1c;font-weight:600;' : 'color:#15803d;font-weight:600;';
					echo '<tr>';
					echo '<td dir="ltr" style="max-width:360px;overflow:hidden;text-overflow:ellipsis;">' . (filter_var($url, FILTER_VALIDATE_URL) ? '<a href="' . esc_url($url) . '" target="_blank" rel="noopener noreferrer">' . esc_html($url) . '</a>' : esc_html($url)) . '</td>';
					echo '<td style="' . esc_attr($st) . '">' . esc_html($verdict !== '' ? $verdict : '-') . '</td>';
					echo '<td dir="ltr">' . esc_html($indexing !== '' ? $indexing : '-') . '</td>';
					echo '<td dir="ltr">' . esc_html($robots !== '' ? $robots : '-') . '</td>';
					echo '<td dir="ltr">' . esc_html($fetch !== '' ? $fetch : '-') . '</td>';
					echo '</tr>';
				}
				echo '</tbody></table></div>';
			} elseif (is_array($data) && !empty($data['error'])) {
				$err = (string) $data['error'];
				if ($err === 'no_valid_urls' || $err === 'no_urls') {
					$err = __('לא נמצאו URL-ים תקינים מהדומיין הנוכחי.', 'icomm-metrix');
				} elseif ($err === 'gsc_not_connected') {
					$err = __('לא מחובר לנתוני חיפוש (GSC). בצעו חיבור ואז נסו שוב.', 'icomm-metrix');
				} elseif ($err === 'unauthorized') {
					$err = __('אין הרשאה לשרת icomm. נסו להתחבר מחדש.', 'icomm-metrix');
				} elseif ($err === 'no_token' || $err === ('missing_refresh' . '_token') || $err === 'not_connected') {
					$err = __('החיבור לגוגל לא הושלם או שפג. התחברו מחדש ואז נסו שוב.', 'icomm-metrix');
				} elseif (stripos($err, 'timed out') !== false || stripos($err, 'timeout') !== false || stripos($err, 'cURL error 28') !== false) {
					$err = __('הבדיקה ארכה יותר מדי (timeout). נסו פחות URL-ים ב«כמה לבדוק עכשיו» ואז שוב.', 'icomm-metrix');
				}
				echo '<div class="notice notice-error" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p>'
					. esc_html(sprintf(__('בדיקת אינדוקס נכשלה: %s', 'icomm-metrix'), $err))
					. '</p></div>';
			} else {
				echo '<div class="notice notice-warning" dir="rtl" lang="he" style="direction:rtl;text-align:right;"><p>'
					. esc_html__('לא התקבלו תוצאות בדיקה. נסו שוב (או הקטינו את מספר ה־URL לבדיקה).', 'icomm-metrix')
					. '</p></div>';
			}
		}
		?>
	</div>

	<h2><?php esc_html_e('נתוני חיפוש', 'icomm-metrix'); ?> <span class="description">(<?php esc_html_e('חינמי', 'icomm-metrix'); ?>)</span></h2>
	<p>
		<?php if (!empty($s['gsc_connected']) && !empty($s['gsc_property'])) : ?>
			<span style="color:#00a32a;font-weight:600;"><?php esc_html_e('מחובר', 'icomm-metrix'); ?></span> <span class="dashicons dashicons-yes-alt" style="color:#00a32a;vertical-align:middle;"></span>
			- <code dir="ltr"><?php echo esc_html((string) $s['gsc_property']); ?></code>
		<?php else : ?>
			<span style="color:#d63638;"><?php esc_html_e('לא מחובר', 'icomm-metrix'); ?></span>
		<?php endif; ?>
	</p>
	<?php if (!empty($s['gsc_last_error'])) : ?>
		<div class="notice notice-error" dir="rtl" lang="he" style="direction:rtl;text-align:right;max-width:820px;">
			<p>
				<?php echo esc_html(IComm_SM_Remote::friendly_google_error((string) $s['gsc_last_error'], 'gsc')); ?>
				<a class="button button-primary" style="margin-right:10px;" href="<?php echo esc_url(IComm_SM_Remote::connect_url('search')); ?>"><?php esc_html_e('חבר נתוני חיפוש מחדש', 'icomm-metrix'); ?></a>
			</p>
		</div>
	<?php endif; ?>

	<p class="description" style="margin-top:-6px;">
		<?php esc_html_e('אין צורך להקליד ידנית אם מופיעה רשימת אתרים אחרי החיבור. אם לא הופיעה רשימה, אפשר להדביק כאן את ה-Property כפי שמופיע ב-GSC (למשל sc-domain:example.com או https://www.example.com/).', 'icomm-metrix'); ?>
	</p>
	<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he" style="max-width:820px;">
		<?php wp_nonce_field('icomm_sm_save_connections'); ?>
		<input type="hidden" name="action" value="icomm_sm_save_connections" />
		<input type="text" name="gsc_property" class="regular-text" dir="ltr" placeholder="sc-domain:example.com" value="<?php echo esc_attr((string) ($s['gsc_property'] ?? '')); ?>" />
		<?php submit_button(__('שמור Property', 'icomm-metrix'), 'secondary', 'submit', false); ?>
	</form>

	<?php if ($gsc_pick !== []) : ?>
		<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he">
			<?php wp_nonce_field('icomm_sm_save_connections'); ?>
			<input type="hidden" name="action" value="icomm_sm_save_connections" />
			<select name="gsc_property" class="regular-text" dir="ltr">
				<option value=""><?php esc_html_e('- בחרו אתר -', 'icomm-metrix'); ?></option>
				<?php if ($gsc_pick_site !== []) : ?>
					<optgroup label="<?php echo esc_attr(__('רלוונטיים לאתר הזה', 'icomm-metrix')); ?>">
						<?php foreach ($gsc_pick_site as $site) : ?>
							<option value="<?php echo esc_attr((string) $site); ?>" <?php selected((string) $s['gsc_property'], (string) $site); ?>><?php echo esc_html((string) $site); ?></option>
						<?php endforeach; ?>
					</optgroup>
				<?php endif; ?>
				<?php if ($gsc_pick_other !== []) : ?>
					<optgroup label="<?php echo esc_attr(__('אתרים נוספים בחשבון', 'icomm-metrix')); ?>">
						<?php foreach ($gsc_pick_other as $site) : ?>
							<option value="<?php echo esc_attr((string) $site); ?>" <?php selected((string) $s['gsc_property'], (string) $site); ?>><?php echo esc_html((string) $site); ?></option>
						<?php endforeach; ?>
					</optgroup>
				<?php elseif ($gsc_pick_site === []) : ?>
					<?php foreach ($gsc_pick as $site) : ?>
						<option value="<?php echo esc_attr((string) $site); ?>" <?php selected((string) $s['gsc_property'], (string) $site); ?>><?php echo esc_html((string) $site); ?></option>
					<?php endforeach; ?>
				<?php endif; ?>
			</select>
			<?php submit_button(__('שמור', 'icomm-metrix')); ?>
		</form>
	<?php endif; ?>

	<p>
		<a class="button button-primary" href="<?php echo esc_url(IComm_SM_Remote::connect_url('search')); ?>"><?php esc_html_e('חבר נתוני חיפוש', 'icomm-metrix'); ?></a>
		<?php if (!empty($s['gsc_connected'])) : ?>
			<a class="button" href="<?php echo esc_url(wp_nonce_url(add_query_arg(['action' => 'icomm_sm_disconnect', 'service' => 'search'], admin_url('admin-post.php')), 'icomm_sm_disconnect_search')); ?>"><?php esc_html_e('נתק', 'icomm-metrix'); ?></a>
		<?php endif; ?>
	</p>

	<h2><?php esc_html_e('Analytics 4', 'icomm-metrix'); ?> <?php echo IComm_SM_Features::pro_badge_html(); ?></h2>
	<?php echo IComm_SM_Features::locked_notice_html(__('Analytics 4', 'icomm-metrix')); ?>
	<div class="<?php echo IComm_SM_Features::can_use('ga4_connect') ? '' : 'icomm-sm-locked-preview'; ?>">
		<p>
			<?php if (!empty($s['ga4_connected']) && !empty($s['ga4_property_id'])) : ?>
				<span style="color:#00a32a;font-weight:600;"><?php esc_html_e('מחובר', 'icomm-metrix'); ?></span> <span class="dashicons dashicons-yes-alt" style="color:#00a32a;vertical-align:middle;"></span>
				- <code dir="ltr"><?php echo esc_html((string) $s['ga4_property_id']); ?></code>
			<?php else : ?>
				<span style="color:#d63638;"><?php esc_html_e('לא מחובר', 'icomm-metrix'); ?></span>
			<?php endif; ?>
		</p>
		<?php if (!empty($s['ga4_last_error'])) : ?>
			<div class="notice notice-error" dir="rtl" lang="he" style="direction:rtl;text-align:right;max-width:820px;"><p><?php echo esc_html((string) $s['ga4_last_error']); ?></p></div>
		<?php endif; ?>

		<p class="description" style="margin-top:-6px;">
			<?php esc_html_e('בדרך כלל אחרי החיבור תופיע רשימת נכסים לבחירה. אם לא, אפשר להדביק ידנית מזהה נכס (למשל properties/123456789 או 123456789).', 'icomm-metrix'); ?>
		</p>
		<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he" style="max-width:820px;">
			<?php wp_nonce_field('icomm_sm_save_connections'); ?>
			<input type="hidden" name="action" value="icomm_sm_save_connections" />
			<input type="text" name="ga4_property_id" class="regular-text" dir="ltr" placeholder="properties/123456789" value="<?php echo esc_attr((string) ($s['ga4_property_id'] ?? '')); ?>" />
			<?php submit_button(__('שמור נכס', 'icomm-metrix'), 'secondary', 'submit', false); ?>
		</form>

		<?php if ($ga4_pick !== []) : ?>
			<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" dir="rtl" lang="he">
				<?php wp_nonce_field('icomm_sm_save_connections'); ?>
				<input type="hidden" name="action" value="icomm_sm_save_connections" />
				<select name="ga4_property_id" class="regular-text" dir="ltr">
					<option value=""><?php esc_html_e('- בחרו נכס -', 'icomm-metrix'); ?></option>
					<?php foreach ($ga4_pick as $prop) : ?>
						<?php if (!is_array($prop)) { continue; } ?>
						<option value="<?php echo esc_attr((string) ($prop['id'] ?? '')); ?>"><?php echo esc_html((string) (($prop['name'] ?? '') . ' (' . ($prop['id'] ?? '') . ')')); ?></option>
					<?php endforeach; ?>
				</select>
				<?php submit_button(__('שמור', 'icomm-metrix')); ?>
			</form>
		<?php endif; ?>

		<p>
			<a class="button button-primary" href="<?php echo esc_url(IComm_SM_Remote::connect_url('stats')); ?>"><?php esc_html_e('חבר אנליטיקס', 'icomm-metrix'); ?></a>
			<?php if (!empty($s['ga4_connected'])) : ?>
				<a class="button" href="<?php echo esc_url(wp_nonce_url(add_query_arg(['action' => 'icomm_sm_disconnect', 'service' => 'stats'], admin_url('admin-post.php')), 'icomm_sm_disconnect_stats')); ?>"><?php esc_html_e('נתק', 'icomm-metrix'); ?></a>
			<?php endif; ?>
		</p>
	</div>
</div>
