<?php
if (!defined('__KIMS__')) exit;

function jusqTelemetryConfigPath()
{
	return $GLOBALS['g']['path_var'].'jusq.telemetry.php';
}

function jusqTelemetryLoad()
{
	$config = array('enabled'=>false);
	$file = jusqTelemetryConfigPath();
	if (is_file($file)) include $file;
	return isset($jusqTelemetry) && is_array($jusqTelemetry) ? array_merge($config,$jusqTelemetry) : $config;
}

function jusqTelemetryCreate($enabled)
{
	if (!$enabled) return false;
	$config = array(
		'enabled'=>true,
		'install_id'=>bin2hex(random_bytes(16)),
		'secret'=>bin2hex(random_bytes(32)),
		'endpoint'=>'https://updates.rilla.kr/telemetry/report.php',
		'last_report'=>0,
	);
	$data = "<?php\n\$jusqTelemetry = ".var_export($config,true).";\n?>\n";
	$file = jusqTelemetryConfigPath();
	if (file_put_contents($file,$data,LOCK_EX) === false) return false;
	@chmod($file,0640);
	return $config;
}

function jusqTelemetrySave($config)
{
	$file = jusqTelemetryConfigPath();
	$data = "<?php\n\$jusqTelemetry = ".var_export($config,true).";\n?>\n";
	$tmp = $file.'.tmp';
	if (file_put_contents($tmp,$data,LOCK_EX) === false || !rename($tmp,$file)) return false;
	@chmod($file,0640);
	return true;
}

function jusqTelemetryReport($event='heartbeat',$force=false,$version='')
{
	$config = jusqTelemetryLoad();
	if (empty($config['enabled']) || empty($config['install_id']) || empty($config['secret']) || empty($config['endpoint'])) return false;
	$now = time();
	if (!$force && $event === 'heartbeat' && $now-(int)($config['last_report'] ?? 0) < 86400) return true;
	$host = strtolower((string)($_SERVER['HTTP_HOST'] ?? php_uname('n')));
	$host = preg_replace('/:\d+$/','',$host);
	$payload = array(
		'install_id'=>$config['install_id'], 'secret'=>$config['secret'], 'event'=>$event,
		'version'=>$version !== '' ? $version : (string)($GLOBALS['d']['admin']['version'] ?? ''),
		'host'=>preg_match('/^[a-z0-9.-]{1,253}$/',$host) ? $host : '',
		'php'=>PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION,
		'os'=>PHP_OS_FAMILY, 'db'=>'mysql', 'sent_at'=>gmdate('c'),
	);
	$body = json_encode($payload,JSON_UNESCAPED_SLASHES);
	if ($body === false) return false;
	$ok = false;
	if (function_exists('curl_init')) {
		$ch = curl_init($config['endpoint']);
		curl_setopt_array($ch,array(CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$body,CURLOPT_HTTPHEADER=>array('Content-Type: application/json'),CURLOPT_RETURNTRANSFER=>true,CURLOPT_CONNECTTIMEOUT=>2,CURLOPT_TIMEOUT=>3,CURLOPT_USERAGENT=>'JusQ-Telemetry/1.0'));
		curl_exec($ch); $ok = curl_errno($ch) === 0 && (int)curl_getinfo($ch,CURLINFO_RESPONSE_CODE) === 202; curl_close($ch);
	} else {
		$context = stream_context_create(array('http'=>array('method'=>'POST','header'=>"Content-Type: application/json\r\nUser-Agent: JusQ-Telemetry/1.0\r\n",'content'=>$body,'timeout'=>3,'ignore_errors'=>true)));
		@file_get_contents($config['endpoint'],false,$context);
		$ok = isset($http_response_header[0]) && strpos($http_response_header[0],'202') !== false;
	}
	if ($ok) { $config['last_report']=$now; jusqTelemetrySave($config); }
	return $ok;
}
?>
