<?php
/**
 * Utility Functions for Sanaprassi Theme
 * 
 * @package Sanaprassi
 */



// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}


/**
 * Debugging Functions
 */

// Buffer for console messages
global $sprassi_console_messages;
if (!isset($sprassi_console_messages) || !is_array($sprassi_console_messages)) {
    $sprassi_console_messages = array();
}

// Log data to the browser console
function _log_to_console($message)
{
	// Only log when debug mode is explicitly enabled.
	// Use error_log to avoid sending any output to the browser during PHP execution.
	if (eval_option(sprssi_options::$debug_mode) || eval_option(sprssi_options::$dev_env)) {
		global $sprassi_console_messages;

		// Convert complex types to string for logging.
		if (is_array($message) || is_object($message)) {
			error_log(print_r($message, true));
			$sprassi_console_messages[] = $message;
		} else {
			error_log((string) $message);
			$sprassi_console_messages[] = (string) $message;
		}

		// Register footer output once (only if WP add_action exists)
		if (function_exists('add_action')) {
			if (!has_action('wp_footer', 'sprassi_print_console_messages')) {
				add_action('wp_footer', 'sprassi_print_console_messages');
				add_action('admin_footer', 'sprassi_print_console_messages');
			}
		}
	}
}

function sprassi_print_console_messages()
{
	global $sprassi_console_messages;

	if (empty($sprassi_console_messages)) {
		return;
	}

	// Try to safely JSON-encode; fall back to strings if needed.
	$json = json_encode($sprassi_console_messages);
	if ($json === false) {
		$fallback = array();
		foreach ($sprassi_console_messages as $m) {
			if (is_array($m) || is_object($m)) {
				$fallback[] = print_r($m, true);
			} else {
				$fallback[] = (string) $m;
			}
		}
		$json = json_encode($fallback);
	}

	// Print once in footer to avoid "headers already sent"
	echo '<script>(function(){var msgs = ' . $json . '; msgs.forEach(function(m){ console.log(m); });})();</script>';

	// Clear buffer
	$sprassi_console_messages = array();
}



function eval_option($option_name)
{
	$option_value = get_option($option_name);
	return $option_value === '1';
}