<?php

define('DATA_JSONL_FILEPATH', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . date('Y') . '.jsonl');

function respondJson(int $statusCode, array $payload): void
{
	http_response_code($statusCode);
	header('Content-Type: application/json; charset=utf-8');
	echo json_encode($payload) . PHP_EOL;
}

function get_curl(string $url, ?array $postdata = null, ?string $cookiedata = null, int $timeout = 60): string|bool
{
	if (! function_exists('curl_init')) {
		trigger_error('CURL not installed in PHP');
	}
	$url = trim($url);
	$ch = curl_init();
	$res = curl_setopt($ch, CURLOPT_URL, $url);

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
	if (!is_null($postdata)) {
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
	}
	if (!is_null($cookiedata)) {
		curl_setopt($ch, CURLOPT_COOKIE, $cookiedata);
	}
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla');
	$ret_data = curl_exec($ch);
	curl_close($ch);
	//print_r($ret_data);
	if (is_null($ret_data)) {
		trigger_error('Error WS: ' . curl_errno($ch) . " - " . curl_error($ch));
	}
	return $ret_data;
}

function telegram(string $to, string $message): string|bool
{
	$json = get_curl('https://telegram.tpsoft.org/sendMessage.php', array('to' => $to, 'message' => $message));
	return json_encode($json, true);
}

function notifyUsers(string $message): void
{
	foreach (['igor', 'veronika'] as $user) {
		try {
			set_error_handler(static function (int $severity, string $errorMessage): bool {
				throw new ErrorException($errorMessage, 0, $severity);
			});
			telegram($user, $message);
		} catch (Throwable $e) {
			error_log('Telegram notification failed for ' . $user . ': ' . $e->getMessage());
		} finally {
			restore_error_handler();
		}
	}
}
