<?php
/**
 * HappyFenceNG Total Enterprise Security Plugin
 * HAPPYWPRESS is a RazorVue Trademark.
 *
 * @package     HappyFenceNG
 * @developer   Simonluca Scillitani
 * @copyright   2025 RazorVue di Scillitani Simonluca
 * @link        https://razorvue.it
 * @author      RazorVue di Scillitani Simonluca
 * @brand       HappyWPress
 * @uri         https://happywpress.com
 * @set all
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**PHPCS -> code compliance: we put useful comments where needed.. */
class HappyFenceNGLOGGER extends HappyFenceNGAlog {
	/**PHPCS -> code compliance: we put useful comments where needed..
	 *
	 * @param string                     $what ... do you think it is?.
	 * @param HappyFenceNGSyslogFacility $facility .. guess it.
	 * @param HappyFenceNGSyslogSeverity $severity ..uh oh? a severity level?.
	 */
	public function log( $what, HappyFenceNGSyslogFacility $facility = HappyFenceNGSyslogFacility::USER, HappyFenceNGSyslogSeverity $severity = HappyFenceNGSyslogSeverity::NOTICE ) {
		global $wp_filesystem;
		define( 'FS_METHOD', 'direct' );
		if ( $this->pre_filter( static::class, $facility, $severity ) ) {

			$upload_dir = wp_upload_dir();
			$dir        = $upload_dir['basedir'] . '/happyfence-logs';

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

			$file = $dir . '/happyfenceng-system.log';

			$line = sprintf(
				"[%s] [%s.%s] [%s] %s\n",
				gmdate( 'Y-m-d H:i:s' ),
				strtolower( $facility->name ),
				strtolower( $severity->name ),
				wp_parse_url( site_url(), PHP_URL_HOST ),
				$what
			);

			self::log_custom( $file, $line );
		} else {
			HappyFenceNGLOGCORE::logcore(
				static::class . "FILTERED LOG by $facility->name $severity->name will not be written",
				HappyFenceNGSyslogFacility::CORE,
				HappyFenceNGSyslogSeverity::AUDIT
			);
		}
	}

	/**PHPCS -> code compliance: we put useful comments where needed..
	 *
	 * @param string $file ... do you think it is?.
	 * @param string $contents .. guess it.
	 */
	private static function log_custom( $file, $contents ) {
		global $wp_filesystem;

		if ( ! $wp_filesystem->exists( $file ) ) {
			$wp_filesystem->touch( $file );
			$wp_filesystem->chmod( $file, 0644 );
		}

		/**We need to use the direct function file_put_contents instead of $wp_filesystem->file_put_contents because mainly it is not possible
		 * to append data to a file and, when using FILE_APPEND the result is unpredictable end raise errors in WordPress.
		 * I wonder who thought that is a MUST DO.
		 */
		if ( $wp_filesystem->is_writable( $file ) ) {
			//phpcs:ignore
			file_put_contents($file, $contents, FILE_APPEND | LOCK_EX);
		} else {
			$wp_filesystem->chmod( $file, 0644 );
			//phpcs:ignore
			file_put_contents($file, $contents, FILE_APPEND | LOCK_EX);
		}
	}
}
