<?php
/**
 * License admin UI helpers v3 (connectivity notice + key masking + manual test).
 * Uses *_v3 function names so a newer copy can load even if an older UI already defined v2 helpers.
 */

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

if (!defined('ICOMM_LIC_CLIENT_UI_API') || (int) ICOMM_LIC_CLIENT_UI_API < 3) {
	if (!defined('ICOMM_LIC_CLIENT_UI_API')) {
		define('ICOMM_LIC_CLIENT_UI_API', 3);
	}
}

if (!function_exists('icomm_lic_client_mask_license_key')) {
	function icomm_lic_client_mask_license_key(string $key, int $visible_tail = 6): string {
		$key = trim($key);
		if ($key === '') {
			return '';
		}
		$visible_tail = max(4, min(12, $visible_tail));
		$len = strlen($key);
		if ($len <= $visible_tail) {
			return str_repeat('*', max(6, $len));
		}
		return str_repeat('*', $len - $visible_tail) . substr($key, -$visible_tail);
	}
}

if (!function_exists('icomm_lic_client_is_masked_license_key')) {
	function icomm_lic_client_is_masked_license_key(string $posted, string $full_key, int $visible_tail = 6): bool {
		$posted = trim($posted);
		$full_key = trim($full_key);
		if ($posted === '' || $full_key === '') {
			return false;
		}
		if ($posted === $full_key) {
			return false;
		}
		if ($posted === icomm_lic_client_mask_license_key($full_key, $visible_tail)) {
			return true;
		}
		$tail = substr($full_key, -$visible_tail);
		if (strlen($posted) < $visible_tail || substr($posted, -$visible_tail) !== $tail) {
			return false;
		}
		$prefix = substr($posted, 0, -$visible_tail);
		return $prefix !== '' && (bool) preg_match('/^[\*•·]+$/u', $prefix);
	}
}

if (!function_exists('icomm_lic_client_connectivity_status_v3')) {
	/**
	 * @return array{state:string,title:string,message:string,class:string,ts:int,error:string,stale:bool}
	 */
	function icomm_lic_client_connectivity_status_v3(string $plugin = ''): array {
		$plugin = sanitize_key($plugin);
		$allowed = function_exists('icomm_lic_client_bg_http_allowed') ? icomm_lic_client_bg_http_allowed() : true;
		$ping = [
			'ok' => false,
			'ts' => 0,
			'http_code' => 0,
			'error' => '',
			'skipped' => false,
		];
		if ($plugin !== '' && function_exists('icomm_lic_client_telemetry_get_ping_status')) {
			$ping = array_merge($ping, icomm_lic_client_telemetry_get_ping_status($plugin));
		}

		$ts = isset($ping['ts']) ? (int) $ping['ts'] : 0;
		$error = isset($ping['error']) ? (string) $ping['error'] : '';
		$http = isset($ping['http_code']) ? (int) $ping['http_code'] : 0;
		$ok = !empty($ping['ok']) && $http === 200 && empty($ping['skipped']);
		$age = $ts > 0 ? max(0, time() - $ts) : 0;
		$stale_fail = !$ok && $ts > 0 && $age > (2 * DAY_IN_SECONDS);

		if (!$allowed) {
			return [
				'state' => 'blocked',
				'title' => 'כרגע אין יציאה לשרת הרישיונות',
				'message' => 'נרשם כשל רשת לאחרונה ולכן בדיקות רקע מושהות זמנית. הרישיון המקומי ממשיך לעבוד. לחצו «בדוק חיבור עכשיו» לנסות שוב.',
				'class' => 'notice-warning',
				'ts' => $ts,
				'error' => $error !== '' ? $error : 'bg_http_cooldown',
				'stale' => false,
			];
		}

		if ($ok) {
			return [
				'state' => 'ok',
				'title' => 'יש גישה לשרת הרישיונות',
				'message' => 'החיבור ל-license.icomm.systems תקין לפי הבדיקה האחרונה.',
				'class' => 'notice-success',
				'ts' => $ts,
				'error' => '',
				'stale' => false,
			];
		}

		if ($stale_fail) {
			return [
				'state' => 'unknown',
				'title' => 'סטטוס חיבור לא מעודכן',
				'message' => 'נשמר כשל ישן (למשל HTTP 0) שאינו מוכיח חסימה עכשיו. הרישיון המקומי יכול להיות תקין. לחצו «בדוק חיבור עכשיו» לעדכון.',
				'class' => 'notice-info',
				'ts' => $ts,
				'error' => $error,
				'stale' => true,
			];
		}

		if ($ts > 0 && ($error !== '' || $http >= 400 || $http === 0)) {
			$detail = $error !== '' ? $error : ('HTTP ' . $http);
			return [
				'state' => 'fail',
				'title' => 'הבדיקה האחרונה נכשלה',
				'message' => 'זה סטטוס שמור מהניסיון האחרון (' . $detail . '), לא בדיקה חיה בעמוד זה. ייתכן כשל זמני ולא חסימה. לחצו «בדוק חיבור עכשיו» לאימות.',
				'class' => 'notice-warning',
				'ts' => $ts,
				'error' => $error,
				'stale' => false,
			];
		}

		return [
			'state' => 'unknown',
			'title' => 'חיבור לשרת הרישיונות טרם נבדק',
			'message' => 'אין עדיין תוצאת ping שמורה. לחצו «בדוק חיבור עכשיו» (timeout קצר).',
			'class' => 'notice-info',
			'ts' => $ts,
			'error' => '',
			'stale' => false,
		];
	}
}

if (!function_exists('icomm_lic_client_run_connectivity_probe')) {
	/**
	 * @return array{ok:bool,http_code:int,error:string,state:string,title:string,message:string,ts:int}
	 */
	function icomm_lic_client_run_connectivity_probe(string $plugin = ''): array {
		$plugin = sanitize_key($plugin);
		if ($plugin === '') {
			$plugin = 'icomm';
		}

		if (function_exists('icomm_lic_client_bg_http_note_success')) {
			icomm_lic_client_bg_http_note_success();
		}

		$base = function_exists('icomm_lic_client_telemetry_rest_base_for')
			? icomm_lic_client_telemetry_rest_base_for($plugin)
			: 'https://license.icomm.systems/wp-json/icomm-lic/v1';
		$url = rtrim((string) $base, '/') . '/ping';
		$site_url = home_url('/');
		$payload = [
			'install_id' => function_exists('icomm_lic_client_telemetry_install_id')
				? icomm_lic_client_telemetry_install_id($plugin)
				: wp_generate_password(20, false, false),
			'site_url' => $site_url,
			'plugin' => $plugin,
			'plugin_version' => function_exists('icomm_lic_client_telemetry_version_for')
				? icomm_lic_client_telemetry_version_for($plugin)
				: '',
			'wp_version' => get_bloginfo('version'),
			'license_state' => function_exists('icomm_lic_client_telemetry_resolve_license_state')
				? icomm_lic_client_telemetry_resolve_license_state($plugin)
				: 'unknown',
			'event' => 'manual_connectivity',
		];

		$GLOBALS['icomm_lic_manual_connectivity_probe'] = 1;
		$res = wp_remote_post($url, [
			'timeout' => 3,
			'redirection' => 0,
			'blocking' => true,
			'headers' => ['Content-Type' => 'application/json; charset=UTF-8'],
			'body' => wp_json_encode($payload),
		]);
		unset($GLOBALS['icomm_lic_manual_connectivity_probe']);

		$http = 0;
		$error = '';
		$ok = false;
		if (is_wp_error($res)) {
			$error = $res->get_error_message();
			if (function_exists('icomm_lic_client_bg_http_note_failure')) {
				icomm_lic_client_bg_http_note_failure();
			}
		} else {
			$http = (int) wp_remote_retrieve_response_code($res);
			$raw = (string) wp_remote_retrieve_body($res);
			$data = json_decode($raw, true);
			$skipped = is_array($data) && !empty($data['skipped']);
			$ok = $http === 200 && is_array($data) && !empty($data['ok']) && !$skipped;
			if (!$ok) {
				$error = is_array($data) && !empty($data['error']) ? (string) $data['error'] : ('HTTP ' . $http);
				if ($http === 0 || $http >= 500) {
					if (function_exists('icomm_lic_client_bg_http_note_failure')) {
						icomm_lic_client_bg_http_note_failure();
					}
				}
			} elseif (function_exists('icomm_lic_client_bg_http_note_success')) {
				icomm_lic_client_bg_http_note_success();
			}
		}

		if (function_exists('icomm_lic_client_telemetry_record_ping_result')) {
			icomm_lic_client_telemetry_record_ping_result($plugin, [
				'ok' => $ok,
				'http_code' => $http,
				'error' => $error,
				'site_url' => $site_url,
				'endpoint' => $url,
			]);
		}

		$status = icomm_lic_client_connectivity_status_v3($plugin);
		return [
			'ok' => $ok,
			'http_code' => $http,
			'error' => $error,
			'state' => (string) $status['state'],
			'title' => (string) $status['title'],
			'message' => (string) $status['message'],
			'ts' => (int) $status['ts'],
		];
	}
}

if (!function_exists('icomm_lic_client_ajax_test_connectivity')) {
	function icomm_lic_client_ajax_test_connectivity(): void {
		if (!current_user_can('manage_options')) {
			wp_send_json_error(['message' => 'Forbidden'], 403);
		}
		check_ajax_referer('icomm_lic_test_connectivity', 'nonce');
		$plugin = isset($_POST['plugin']) ? sanitize_key((string) wp_unslash($_POST['plugin'])) : '';
		if ($plugin === '') {
			wp_send_json_error(['message' => 'Missing plugin'], 400);
		}
		wp_send_json_success(icomm_lic_client_run_connectivity_probe($plugin));
	}
}

if (!has_action('wp_ajax_icomm_lic_test_connectivity', 'icomm_lic_client_ajax_test_connectivity')) {
	add_action('wp_ajax_icomm_lic_test_connectivity', 'icomm_lic_client_ajax_test_connectivity');
}

if (!function_exists('icomm_lic_client_render_connectivity_notice_v3')) {
	function icomm_lic_client_render_connectivity_notice_v3(string $plugin = ''): void {
		if (!is_admin()) {
			return;
		}
		$plugin = sanitize_key($plugin);
		$status = icomm_lic_client_connectivity_status_v3($plugin);
		$title = (string) $status['title'];
		$message = (string) $status['message'];
		$ts = (int) $status['ts'];
		$state = (string) $status['state'];
		$bg = '#f0f6fc';
		$border = '#72aee6';
		$icon = 'info';
		if ($state === 'ok') {
			$bg = '#edfaef';
			$border = '#00a32a';
			$icon = 'yes-alt';
		} elseif ($state === 'blocked' || $state === 'fail') {
			$bg = '#fcf9e8';
			$border = '#dba617';
			$icon = 'warning';
		}
		$uid = 'icomm-lic-conn-' . preg_replace('/[^a-z0-9_-]/i', '', $plugin !== '' ? $plugin : 'x');
		$nonce = wp_create_nonce('icomm_lic_test_connectivity');
		$ajax = admin_url('admin-ajax.php');
		?>
		<div id="<?php echo esc_attr($uid); ?>" class="icomm-lic-connectivity-box" dir="rtl" data-plugin="<?php echo esc_attr($plugin); ?>" data-nonce="<?php echo esc_attr($nonce); ?>" data-ajax="<?php echo esc_url($ajax); ?>" style="max-width:820px;margin:8px 0 12px;padding:10px 12px;background:<?php echo esc_attr($bg); ?>;border:1px solid <?php echo esc_attr($border); ?>;border-right:4px solid <?php echo esc_attr($border); ?>;border-radius:4px;box-sizing:border-box;">
			<p class="icomm-lic-conn-title" style="margin:0 0 4px;font-size:13px;line-height:1.4;">
				<span class="dashicons dashicons-<?php echo esc_attr($icon); ?>" style="color:<?php echo esc_attr($border); ?>;vertical-align:middle;margin-left:4px;"></span>
				<strong><?php echo esc_html($title); ?></strong>
			</p>
			<p class="icomm-lic-conn-msg" style="margin:0;font-size:13px;line-height:1.4;"><?php echo esc_html($message); ?></p>
			<div class="icomm-lic-conn-ts-row" style="display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:6px 0 0;color:#646970;font-size:12px;line-height:1.4;">
				<span class="icomm-lic-conn-ts">
					<?php if ($ts > 0) : ?>
						<?php echo esc_html('בדיקה אחרונה (שמורה): '); ?><span class="icomm-lic-conn-ts-text"><?php echo esc_html(wp_date('d/m/Y H:i', $ts)); ?></span>
					<?php else : ?>
						<span class="icomm-lic-conn-ts-text"></span>
					<?php endif; ?>
				</span>
				<button type="button" class="button button-secondary button-small icomm-lic-conn-test-btn"><?php echo esc_html('בדוק חיבור עכשיו'); ?></button>
				<span class="icomm-lic-conn-busy" hidden style="color:#646970;">בודק… (עד 3 שניות)</span>
			</div>
		</div>
		<script>
		(function () {
			var box = document.getElementById(<?php echo wp_json_encode($uid); ?>);
			if (!box || box.getAttribute('data-bound') === '1') { return; }
			box.setAttribute('data-bound', '1');
			var btn = box.querySelector('.icomm-lic-conn-test-btn');
			var busy = box.querySelector('.icomm-lic-conn-busy');
			if (!btn) { return; }
			btn.addEventListener('click', function () {
				btn.disabled = true;
				if (busy) { busy.hidden = false; }
				var body = new FormData();
				body.append('action', 'icomm_lic_test_connectivity');
				body.append('nonce', box.getAttribute('data-nonce') || '');
				body.append('plugin', box.getAttribute('data-plugin') || '');
				fetch(box.getAttribute('data-ajax') || (window.ajaxurl || ''), {
					method: 'POST',
					credentials: 'same-origin',
					body: body
				}).then(function (r) { return r.json(); }).then(function (json) {
					var d = (json && json.data) ? json.data : {};
					var ok = !!(json && json.success && d.ok);
					var titleEl = box.querySelector('.icomm-lic-conn-title strong');
					var msgEl = box.querySelector('.icomm-lic-conn-msg');
					var tsTextEl = box.querySelector('.icomm-lic-conn-ts-text');
					if (titleEl) { titleEl.textContent = d.title || (ok ? 'יש גישה לשרת הרישיונות' : 'הבדיקה נכשלה'); }
					if (msgEl) { msgEl.textContent = d.message || d.error || ''; }
					if (tsTextEl && d.ts) {
						tsTextEl.textContent = new Date(parseInt(d.ts, 10) * 1000).toLocaleString();
					}
					box.style.background = ok ? '#edfaef' : '#fcf9e8';
					box.style.borderColor = ok ? '#00a32a' : '#dba617';
					box.style.borderRightColor = ok ? '#00a32a' : '#dba617';
				}).catch(function () {
					var msgEl = box.querySelector('.icomm-lic-conn-msg');
					if (msgEl) { msgEl.textContent = 'בדיקת החיבור נכשלה (שגיאת רשת מקומית).'; }
				}).finally(function () {
					btn.disabled = false;
					if (busy) { busy.hidden = true; }
				});
			});
		})();
		</script>
		<?php
	}
}

// Prefer v3 wherever old call sites still use the unversioned name.
if (!function_exists('icomm_lic_client_render_connectivity_notice')) {
	function icomm_lic_client_render_connectivity_notice(string $plugin = ''): void {
		icomm_lic_client_render_connectivity_notice_v3($plugin);
	}
} elseif (!function_exists('icomm_lic_client_render_connectivity_notice_v3_alias_installed')) {
	// Old render already exists: expose helper for call sites that prefer v3 explicitly.
	function icomm_lic_client_render_connectivity_notice_v3_alias_installed(): bool {
		return true;
	}
}

if (!function_exists('icomm_lic_client_connectivity_status') && function_exists('icomm_lic_client_connectivity_status_v3')) {
	function icomm_lic_client_connectivity_status(string $plugin = ''): array {
		return icomm_lic_client_connectivity_status_v3($plugin);
	}
}
