<?php
namespace Prodigy\Includes\Helpers;

/**
 *
 * Support Prodigy Logger plugin
 *
 * @version    3.0.2
 * @package    Prodigy
 * @subpackage Prodigy/includes
 */
class Prodigy_Logger {

	const TYPE_ERROR   = 'error';
	const TYPE_WARNING = 'warning';
	const TYPE_INFO    = 'info';

	/**
	 * Log a message based on type.
	 *
	 * @param string $type
	 * @param string $message
	 * @param string $query_url
	 * @param string $data
	 */
	public static function add_record( string $type, string $message = '', string $query_url = '', string $data = '' ) {
		if ( empty( $type ) ) {
			self::log_error( $message, $query_url, 'Invalid type.' );
			return;
		}

		switch ( $type ) {
			case self::TYPE_INFO:
				self::log_info( $message, $query_url, $data );
				break;

			case self::TYPE_WARNING:
				self::log_warning( $message, $query_url, $data );
				break;

			case self::TYPE_ERROR:
				self::log_error( $message, $query_url, $data );
				break;
		}
	}

	/**
	 * @param   string $message
	 * @param   string $query_url
	 * @param   string $data
	 *
	 * @return void
	 */
	private static function log_info( string $message, string $query_url, string $data ) {
		$decoded_data = json_decode( $data, true );
		if ( json_last_error() === JSON_ERROR_NONE ) {
			$pretty_data = json_encode( $decoded_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
		}

		self::trigger_logger( $message, $query_url, $pretty_data ?? '', self::TYPE_INFO );
	}

	/**
	 * @param   string $message
	 * @param   string $query_url
	 * @param   string $data
	 *
	 * @return void
	 */
	private static function log_warning( string $message, string $query_url, string $data ) {
		self::trigger_logger( $message, $query_url, 'Empty or invalid response body.' . $data, self::TYPE_WARNING );
	}

	/**
	 * @param   string $message
	 * @param   string $query_url
	 * @param   string $error_message
	 *
	 * @return void
	 */
	private static function log_error( string $message, string $query_url, string $error_message ) {
		self::trigger_logger( $message, $query_url, $error_message, self::TYPE_ERROR );
	}

	/**
	 * @param   string $message
	 * @param   string $query_url
	 * @param   string $body
	 * @param   string $type
	 *
	 * @return void
	 */
	private static function trigger_logger( string $message, string $query_url, string $body, string $type ) {
		do_action( 'logger', $message . ' ' . $query_url . "\n" . $body, $type );
	}
}
