<?php

if (!defined('WPINC')) {
	die;
}

class AthenaLogger {

	const PREFIX = '[Athena] ';
	const ERROR_PREFIX = '[Athena ERROR] ';

	// Log info/debug messages - ONLY if WP_DEBUG_LOG = true
	public static function info($message) {
		if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
			error_log(self::PREFIX . $message);
		}
	}
	// Log error messages - ALWAYS (critical for troubleshooting)
	public static function error($message) {
		error_log(self::ERROR_PREFIX . $message);
	}

	// Similar to the info function but ensures that print_r() is not displayed outside of our if conditions
	public static function debug(callable $callback) {
		if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
			$message = $callback(); // The callback is executed ONLY if WP_DEBUG_LOG = true
			error_log(self::PREFIX . $message);
		}
	}

	public static function reindexLogs($message, $type = 'info') {
		$prefix = '';
		$type = strtolower($type);

		if ($type === 'error') {
			$prefix = '[ERROR] ';
		} elseif ($type === 'success') {
			$prefix = '[SUCCESS] ';
		} else {
			$prefix = '[INFO] ';
		}

		self::athenaCustomLog($prefix . $message);
	}

	// Writes logs to a custom file for the frontend UI to read
	private static function athenaCustomLog($message) {
		$upload_dir = wp_upload_dir();
		$athena_dir = trailingslashit($upload_dir['basedir']) . 'athena';

		if (!file_exists($athena_dir)) {
			wp_mkdir_p($athena_dir);
		}

		// Prevent direct access to the folder
		$htaccess_file = trailingslashit($athena_dir) . '.htaccess';
		if (!file_exists($htaccess_file)) {
			file_put_contents($htaccess_file, "Deny from all\n");
		}

		$log_file = trailingslashit($athena_dir) . 'athena-reindex.log';
		$timestamp = current_time('mysql');
		$formatted_message = "[{$timestamp}] {$message}\n\n";

		error_log($formatted_message, 3, $log_file);
	}
}