<?php

	namespace Honeypot\Log;

	use \VV;

	// Save logs to this directory
	const LOG_DIR = "logs/";
	// Use this as the default fingerprint if we don't get one from the client
	const DEFAULT_FINGERPRINT = "undefined";

	function save_log(object $data): bool {
		// Logging is explicitly disabled. No environment variable is treated as enabled
		if (!($_ENV["LOG_ENABLED"] ?? true)) {
			return false;
		}

		$data->fingerprint ??= DEFAULT_FINGERPRINT;
		$log_dir = VV::root(LOG_DIR . $data->fingerprint);

		// Create log directory for this fingerprint if it's the first time we've seen it
		if (!is_dir($log_dir)) {
			if (!mkdir($log_dir)) {
				// Failed to create directory
				return false;
			}
		}

		// Include server data
		$data->server = (object) $_SERVER;

		// Write log file
		return file_put_contents($log_dir . "/" . microtime() . ".json", json_encode($data));
	}