<?php

/**
 * Logging utility for Hypodash.
 */
class Hypodash_Logger
{

	/**
	 * Log directory name within the uploads folder.
	 */
	const LOG_DIR = 'hypodash-logs';

	/**
	 * Main log file name.
	 */
	const LOG_FILE = 'webhook.log';

	/**
	 * Get the full path to the log file.
	 *
	 * @return string
	 */
	public static function get_log_file()
	{
		$upload_dir = wp_upload_dir();
		$log_dir    = $upload_dir['basedir'] . '/' . self::LOG_DIR;

		// Ensure directory exists with proper permissions
		if (! is_dir($log_dir)) {
			if (! wp_mkdir_p($log_dir)) {
				// Fallback to plugin directory if uploads dir is not writable
				$log_dir = plugin_dir_path(dirname(__FILE__)) . self::LOG_DIR;
				if (! is_dir($log_dir)) {
					wp_mkdir_p($log_dir);
				}
			}
		}

		return $log_dir . '/' . self::LOG_FILE;
	}

	/**
	 * Log a message with timestamp.
	 *
	 * @param string $level   Log level (INFO, WARNING, ERROR, DEBUG).
	 * @param string $message Message to log.
	 * @param array  $context Optional contextual data.
	 */
	public static function log($level, $message, $context = array())
	{
		$log_file = self::get_log_file();

		$timestamp = current_time('Y-m-d H:i:s');
		$level     = strtoupper($level);
		$context_str = '';

		if (! empty($context)) {
			$context_str = ' | ' . wp_json_encode($context);
		}

		$log_entry = sprintf("[%s] %s: %s%s\n", $timestamp, $level, $message, $context_str);

		// Ensure parent directory exists before attempting to write
		$log_dir = dirname($log_file);
		if (! is_dir($log_dir)) {
			wp_mkdir_p($log_dir);
		}

		// Prefer WP_Filesystem for file operations
		$written = false;
		if (! function_exists('request_filesystem_credentials')) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}
		// Initialize WP_Filesystem. This will populate global $wp_filesystem.
		WP_Filesystem();
		global $wp_filesystem;
		if (is_object($wp_filesystem)) {
			$log_dir_fs = dirname($log_file);
			// Ensure directory exists via WP_Filesystem
			if (! $wp_filesystem->is_dir($log_dir_fs)) {
				$wp_filesystem->mkdir($log_dir_fs);
			}

			// Append to existing file by reading and writing the combined contents
			$existing = '';
			if ($wp_filesystem->exists($log_file)) {
				$existing = $wp_filesystem->get_contents($log_file);
			}
			$contents = $existing . $log_entry;
			$written = $wp_filesystem->put_contents($log_file, $contents, FS_CHMOD_FILE);
		}

		// Final fallback: use native file_put_contents if WP_Filesystem unavailable
		if (! $written) {
			$result = @file_put_contents($log_file, $log_entry, FILE_APPEND | LOCK_EX);
			$written = (false !== $result);
		}
	}

	/**
	 * Log an info-level message.
	 *
	 * @param string $message Message to log.
	 * @param array  $context Optional context.
	 */
	public static function info($message, $context = array())
	{
		self::log('INFO', $message, $context);
	}

	/**
	 * Log a warning-level message.
	 *
	 * @param string $message Message to log.
	 * @param array  $context Optional context.
	 */
	public static function warning($message, $context = array())
	{
		self::log('WARNING', $message, $context);
	}

	/**
	 * Log an error-level message.
	 *
	 * @param string $message Message to log.
	 * @param array  $context Optional context.
	 */
	public static function error($message, $context = array())
	{
		self::log('ERROR', $message, $context);
	}

	/**
	 * Log a debug-level message.
	 *
	 * @param string $message Message to log.
	 * @param array  $context Optional context.
	 */
	public static function debug($message, $context = array())
	{
		self::log('DEBUG', $message, $context);
	}

	/**
	 * Get the log file URL for easy access.
	 *
	 * @return string
	 */
	public static function get_log_url()
	{
		$log_file = self::get_log_file();
		$upload_dir = wp_upload_dir();

		// Check if log is in uploads directory
		if (strpos($log_file, $upload_dir['basedir']) === 0) {
			return $upload_dir['baseurl'] . '/' . self::LOG_DIR . '/' . self::LOG_FILE;
		}

		// Fallback: log is in plugin directory
		return plugins_url(self::LOG_DIR . '/' . self::LOG_FILE, dirname(__FILE__));
	}
}
